最近项目里面需要用到Java发送http请求,由于发送https请求有点复杂,暂时不考虑

HttpURLConnection

HttpURLConnection是一种多用途、轻量极的HTTP客户端,使用它来进行HTTP操作可以适用于大多数的应用程序。

HttpURLConnection是Java的标准类,它继承自URLConnection,可用于向指定网站发送GET请求、POST请求。它在URLConnection的基础上提供了如下便捷的方法:

int getResponseCode(); // 获取服务器的响应代码。
String getResponseMessage(); // 获取服务器的响应消息。
String getResponseMethod(); // 获取发送请求的方法。
void setRequestMethod(String method); // 设置发送请求的方法。

如何使用

HTTP请求方法有8种,分别是GET、POST、DELETE、PUT、HEAD、TRACE、CONNECT 、OPTIONS。其中PUT、DELETE、POST、GET分别对应着增删改查。

GET:请求获取Request-URI所标识的资源
POST:在Request-URI所标识的资源后附加新的数据
HEAD:请求获取由Request-URI所标识的资源的响应消息报头
PUT: 请求服务器存储一个资源,并用Request-URI作为其标识
DELETE :请求服务器删除Request-URI所标识的资源
TRACE : 请求服务器回送收到的请求信息,主要用于测试或诊断
CONNECT: HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。
OPTIONS :请求查询服务器的性能,或者查询与资源相关的选项和需求

返回的数据格式化json   用的是 com.google.gson.*;

开始

(1)包

import com.google.gson.*;
import java.io.*;
import java.net.*;

(2)发送GET请求

public static JsonObject getXpath(String requestUrl) {
String res = "";
JsonObject object = null;
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
System.out.println(urlCon.getResponseCode());
if (200 == urlCon.getResponseCode()) {
InputStream is = urlCon.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String str = null;
while ((str = br.readLine()) != null) {
buffer.append(str);
}
br.close();
isr.close();
is.close();
res = buffer.toString();
JsonParser parse = new JsonParser();
object = (JsonObject) parse.parse(res);
} else {
throw new Exception("连接失败");
}
} catch (Exception e) {
e.printStackTrace();
}
return object;
}

(3)发送POST请求

public static JsonObject postDownloadJson(String path, String post) {
URL url = null;
try {
url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// 提交模式
httpURLConnection.setRequestMethod("POST");
//连接超时 单位毫秒
httpURLConnection.setConnectTimeout(10000);
//读取超时 单位毫秒
httpURLConnection.setReadTimeout(2000);
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
//post的参数 xx=xx&yy=yy
printWriter.write(post);
// flush输出流的缓冲
printWriter.flush();
//开始获取数据
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len;
byte[] arr = new byte[1024];
while ((len = bis.read(arr)) != -1) {
bos.write(arr, 0, len);
bos.flush();
}
bos.close();
JsonParser parse = new JsonParser();
return (JsonObject) parse.parse(bos.toString("utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

如果需要用到登录情况,可以先发送登录请求保存cookie,第二次发送就可以请求了

(4)保存cookie

通过这两行代码就可以把网站返回的cookie信息存储起来,下次访问网站的时候,自动帮你把cookie信息带上。

//存储cookie
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);

通过返回的json获取值(子节点)

JsonElement cookie = res.get("data").getAsJsonObject().get("cookie");

超时无响应问题设置

//连接超时 单位毫秒
httpURLConnection.setConnectTimeout(10000);
//读取超时 单位毫秒
httpURLConnection.setReadTimeout(2000);

最新文章

  1. C# Winform防止一个程序重复运行
  2. IIS7.0发布Web服务-0001
  3. linux运行级别
  4. javascript 利用匿名函数对象给你异步回调方法传参数
  5. (转)JAVA之桥接模式
  6. 如何把android中布局文件(.xml)与相关的类(.java)进行关联?
  7. 带着问题学 Spring MVC 源码: 一、概述
  8. 问题解决——SolidWorks 已停止工作 (Windows7 + SolidWorks 2010 SP0.0)
  9. 在fedora 桌面上添加应用程序
  10. Cstring获取第N个字符
  11. php 汉字排序
  12. Codeblocks快捷键
  13. c# 去除字符串中重复字符
  14. PostgreSQL查询优化之子查询优化
  15. [SHOI2008]汉诺塔
  16. 2015 多校联赛 ——HDU5373(模拟)
  17. EasyPR源码剖析(5):车牌定位之偏斜扭转
  18. OpenStack中的虚拟机(/dev/mapper/centos-root)进行磁盘扩容
  19. Python写黑客小工具,360免杀
  20. Hanoi问题 算法

热门文章

  1. SQL题(子文章)(持续更新)
  2. springboot项目获取resource下的文件
  3. Ubuntu16.04启动tomcat缓慢问题之解决方案
  4. weblogic介绍
  5. 时间控件My97DatePicker事件监听及用法
  6. 随机森林算法OOB_SCORE最佳特征选择
  7. [V5] ARM: dts: Change i2s compatible string on exynos5250【转】
  8. 2019年逾期率上升_24家头部P2P平台最新运营数据解读:8家近一年逾期率走势曝光
  9. python3 selenium模块Chrome设置代理ip的实现
  10. Flutter -------- Http库 网络请求封装(HttpController)