简介
现在大多数的http请求都是使用 restful 风格,系统之间的交流也是使用 restful 风格的http请求,所以就写了一个工具类来简化这些工作。
点击查看工具类代码
这个工具类是基于 HttpURLConnection 写的。
并依赖 jackson 对 json 进行解析,你可以在代码里改成其它的 json 解析工具。
使用方法
- 请求示例
try {
//发送GET请求获取用户信息,默认GET请求
RestfulHttpClient.HttpResponse response = RestfulHttpClient
.getClient("http://localhost/user/{id}")
.addPathParam("id", "100")
.request();
if(response.getCode() == 200){
User user = response.getContent(User.class);
}
} catch (IOException e) { }
try {
//发送PUT请求更新用户信息
RestfulHttpClient.HttpResponse response = RestfulHttpClient
.getClient("http://localhost/user/{id}")
.put()
.addPathParam("id", "100")
.body(user)
.request();
if(response.getCode() == 200){
String result = response.getContent();
}
} catch (IOException e) { }
try {
/*-- 2019-4-16 新增:发送异步请求 --*/
//发送异步请求
Future<HttpResponse> future = getClient("https://www.baidu.com")
.asyncRequest();
System.out.println("do something else");
RestfulHttpClient.HttpResponse response = future.get();
if(response.getCode() == 200){
String result = response.getContent();
}
} catch (IOException | InterruptedException | ExecutionException e) { }
- 文件下载
// 指定响应结果为文件流之后,返回的响应对象为 HttpResponseStream
HttpResponseStream request = (HttpResponseStream) RestfulHttpClient.getClient("http://down10.zol.com.cn/office/gongzibiao.rar")
// 指定响应结果为文件流
.download()
// 发起请求
.request();
if (request.getCode() == 200) {
// 文件名,自动识别,可能为空
System.out.println(request.getFilename());
// 文件大小,如果为-1或0是服务器端没返回文件大小
System.out.println(request.getFileLength());
// 保存文件,下载几种方式只能使用一种,保存之后不能再使用这些方法
// 保存为指定文件
request.saveTo("D:/test.rar");
// 保存到指定目录,文件名为自动识别的文件名
request.saveTo("D:/");
// 保存到指定目录下,并指定文件名
request.saveTo("D:/download", "test.rar");
// 输出到指定输出流
request.saveTo(new ByteArrayOutputStream());
// 直接获取影响数据
byte[] data = request.getData();
} else {
// 下载失败,输出结果
System.out.println(request.getContent());
}
- 创建一个请求客户端
RestfulHttpClient.HttpClient client = RestfulHttpClient.getClient(url);
- 设置请求方式
默认GET请求
client.get();
client.post();
client.put();
client.patch();
client.delete();
- 设置请求头
// 设置全局默认请求头,每次请求都会带上这些请求头
RestfulHttpClient.setDefaultHeaders(headersMap);
// -- 设置本次请求头 --
//添加多个请求头
client.addHeaders(headersMap);
//添加一个请求头
client.addHeader("key", "value");
//重置请求头,会保留全局默认请求头
client.headers(headersMap);
- 添加 url 路径参数 pathParams
什么是路径参数,如:http://localhost/user/{id}
中的id
//添加一个参数,最后请求url变为:http://localhost/user/100
client.addPathParam("id", "100");
//添加多个参数,不会清空原来的参数
client.postParams(paramsMap);
- 添加请求参数 queryParams
什么是请求参数,请求参数就是url问号后面的参数,如http://localhost/user?page=1&rows=10
中的page=1&rows=10
//原请求url为:http://localhost/user
//最终请求url为:http://localhost/user?page=1
client.addQueryParam("page", "1");
//添加多个参数,不会清空原来的参数
client.queryParams(paramsMap);
- 添加表单参数 postParams
什么是表单参数,表单参数跟请求参数的形式一样name1=value1&name2=value2
,不过不是通过url地址后面问号提交,而是通过请求体提交,如 post 提交
//添加一个参数,不会清空原来的参数
client.addPostParam("page", "1");
//添加多个参数,不会清空原来的参数
client.postParams(paramsMap);
- 添加请求体参数 body
什么是请求体,不懂请求百度http 请求体
。
请求体参数可以是一个值或一个对象,如果是对象最终会转为json字符串提交。
请求体参数body与表单参数postParams,不能同时添加,如果同时添加了两个参数最终只会发送请求体参数body。
//添加请求体,如果重复添加会覆盖之前的值
client.body(obj);
- 发起请求并获取响应结果
//发起请求,获取响应结果
RestfulHttpClient.HttpResponse response = client.request();
//根据状态码判断请求是否成功
if(response.getCode() == 200){
//获取响应内容
String result = response.getContent();
}
- 添加https请求信任
//添加全局信任
RestfulHttpClient.addInitializer(new TrustAllHttpsInitializer());
//本次请求添加信任
RestfulHttpClient.HttpResponse response = RestfulHttpClient.getClient(url)
.addInitializer(new TrustAllHttpsInitializer())
.request(); //发起请求
- 添加自定义https证书认证
实现RestfulHttpClient.URLConnectionInitializer
接口,并添加到RestfulHttpClient.addInitializer(URLConnectionInitializer)
public class MyConnectionInitializer implements RestfulHttpClient.URLConnectionInitializer {
@Override
public HttpURLConnection init(HttpURLConnection connection, RestfulHttpClient.HttpClient client) {
//添加证书
return connection;
}
}
// 证书设置全局请求有效
RestfulHttpClient.addInitializer(new MyConnectionInitializer());
// 证书只有本次请求有效
RestfulHttpClient.getClient(url).addInitializer(new MyConnectionInitializer()).request();