Java中的HTTP请求

http-requst

最大的特点是基于URLConnection实现,不依赖HttpClient

URLConnection的优点是内置于Java标准库中,无需引入其他依赖。而HttpClient需要引入额外的包和依赖。

引用

1
2
3
4
5
<dependency>
<groupId>com.github.kevinsawicki</groupId>
<artifactId>http-request</artifactId>
<version>5.6</version>
</dependency>

Get请求

1
2
3
public static HttpRequest get(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_GET);
}

获取响应报文

1
2
String response = HttpRequest.get("http://www.baidu.com").body();
System.out.println("Response was: "+response);

获取响应码

1
int code = HttpRequest.get("http://google.com").code();

请求传参

第一种写法

1
HttpRequest request = HttpRequest.get("http://google.com", true, 'macId', "10051", "size", "测试机构");

第二种

1
2
3
4
5
Map data = new HashMap(); 
data.put("macId", "10051");
data.put("macName", "测试机构");
String result =HttpRequest.get("http://google.com").form(data).body();
System.out.println("result:" + resp);

Post请求

Form形式

1
2
3
4
Map<String, String> data = new HashMap<String, String>();
data.put("user", "A User");\
data.put("state", "CA");\
HttpRequest request = HttpRequest.post(url).form(data);

JSON形式

1
2
3
4
5
6
7
8
9
JsonObject jsonContent = new JsonObject();
jsonContent.addProperty("content",msgBody);
JsonObject jsonData = new JsonObject();
jsonData.add("data",jsonContent);
jsonData.addProperty("subtype",subType);
HttpRequest httpRequest = HttpRequest.post(url).acceptJson();
httpRequest.send(jsonData.toString());
int code = httpRequest.code();
String body = httpRequest.body();

文件

1
2
3
4
HttpRequest request = HttpRequest.post("url”);                              
request.header("Content-Type", "multipart/form-data;boundary=AaB03x");
request.part("name","makeshuo");
request.part("imagefile", "test.log", "image/jpeg", new File("d:/test/test.jpg"));

Hutool

一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅。

引用

1
2
3
4
5
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.19</version>
</dependency>

Get请求

1
2
3
4
5
6
7
8
9
10
11
// 最简单的HTTP请求,可以自动通过header等信息判断编码,不区分HTTP和HTTPS
String result1= HttpUtil.get("https://www.baidu.com");

// 当无法识别页面编码的时候,可以自定义请求页面的编码
String result2= HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8);

//可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "北京");

String result3= HttpUtil.get("https://www.baidu.com", paramMap);

Post请求

1
2
3
4
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "北京");

String result= HttpUtil.post("https://www.baidu.com", paramMap);

Form形式

1
2
3
4
5
6
7
//链式构建请求
String result2 = HttpRequest.post(url)
.header(Header.USER_AGENT, "Hutool http")//头信息,多个头信息多次调用此方法即可
.form(paramMap)//表单内容
.timeout(20000)//超时,毫秒
.execute().body();
Console.log(result2);

JSON形式

1
2
3
4
String json = ...;
String result2 = HttpRequest.post(url)
.body(json)
.execute().body();

文件上传

1
2
3
4
5
HashMap<String, Object> paramMap = new HashMap<>();
//文件上传只需将参数中的键指定(默认file),值设为文件对象即可,对于使用者来说,文件上传与普通表单提交并无区别
paramMap.put("file", FileUtil.file("D:\\face.jpg"));

String result= HttpUtil.post("https://www.baidu.com", paramMap);

文件下载

因为Hutool-http机制问题,请求页面返回结果是一次性解析为byte[]的,如果请求URL返回结果太大(比如文件下载),那内存会爆掉,因此针对文件下载HttpUtil单独做了封装。文件下载在面对大文件时采用流的方式读写,内存中只是保留一定量的缓存,然后分块写入硬盘,因此大文件情况下不会对内存有压力。

1
2
3
4
5
String fileUrl = "http://mirrors.sohu.com/centos/8.4.2105/isos/x86_64/CentOS-8.4.2105-x86_64-dvd1.iso";

//将文件下载后保存在E盘,返回结果为下载文件大小
long size = HttpUtil.downloadFile(fileUrl, FileUtil.file("e:/"));
System.out.println("Download size: " + size);

如果想获取下载进度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//带进度显示的文件下载
HttpUtil.downloadFile(fileUrl, FileUtil.file("e:/"), new StreamProgress(){

@Override
public void start() {
Console.log("开始下载。。。。");
}

@Override
public void progress(long progressSize) {
Console.log("已下载:{}", FileUtil.readableFileSize(progressSize));
}

@Override
public void finish() {
Console.log("下载完成!");
}
});

配置代理

如果代理无需账号密码,可以直接:

1
2
3
4
5
String result2 = HttpRequest.post(url)
.setHttpProxy("127.0.0.1", 9080)
.body(json)
.execute()
.body();

如果需要自定其他类型代理或更多的项目,可以:

1
2
3
4
5
String result2 = HttpRequest.post(url)
.setProxy(new Proxy(Proxy.Type.HTTP,new InetSocketAddress(host, port))
.body(json)
.execute()
.body();

如果遇到https代理错误Proxy returns "HTTP/1.0 407 Proxy Authentication Required",可以尝试:

1
2
3
4
5
6
7
8
9
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
Authenticator.setDefault(
new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authUser, authPassword.toCharArray());
}
}
);

Feign

可参考

https://www.psvmc.cn/article/2019-02-14-springcloud-feign.html