共计 8930 个字符,预计需要花费 23 分钟才能阅读完成。
作者:何甜甜在吗
https://juejin.im/post/684490…
写在后面
为什么会写这篇文章,起因于和敌人的聊天
img
这又涉及到我的常识盲区了,首先来一波面向百度学习,间接依据关键字 httpclient 和 okhttp 的区别、性能比拟进行搜寻,没有找到想要的答案,于是就去 overstackflow 上看看是不是有人问过这个问题,果然不会让你悲观的
img
所以从应用、性能、超时配置方面进行比拟
应用
HttpClient 和 OkHttp 个别用于调用其它服务,个别服务裸露进去的接口都为 http,http 罕用申请类型就为 GET、PUT、POST 和 DELETE,因而次要介绍这些申请类型的调用
HttpClient 应用介绍
应用 HttpClient 发送申请次要分为一下几步骤:
- 创立 CloseableHttpClient 对象或 CloseableHttpAsyncClient 对象,前者同步,后者为异步
- 创立 Http 申请对象
- 调用 execute 办法执行申请,如果是异步申请在执行之前需调用 start 办法
创立连贯:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
该连贯为同步连贯
GET 申请:
@Test
public void testGet() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE\_URL, api);
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println(EntityUtils.toString(response.getEntity()));
}
应用 HttpGet 示意该连贯为 GET 申请,HttpClient 调用 execute 办法发送 GET 申请
PUT 申请:
@Test
public void testPut() throws IOException {
String api = "/api/user";
String url = String.format("%s%s", BASE\_URL, api);
HttpPut httpPut = new HttpPut(url);
UserVO userVO = UserVO.builder().name("h2t").id(16L).build();
httpPut.setHeader("Content-Type", "application/json;charset=utf8");
httpPut.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPut);
System.out.println(EntityUtils.toString(response.getEntity()));
}
POST 申请:
- 增加对象
@Test
public void testPost() throws IOException {
String api = "/api/user";
String url = String.format("%s%s", BASE\_URL, api);
HttpPost httpPost = new HttpPost(url);
UserVO userVO = UserVO.builder().name("h2t2").build();
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
httpPost.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPost);
System.out.println(EntityUtils.toString(response.getEntity()));
}
该申请是一个创建对象的申请,须要传入一个 json 字符串
- 上传文件
@Test
public void testUpload1() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE\_URL, api);
HttpPost httpPost = new HttpPost(url);
File file = new File("C:/Users/hetiantian/Desktop/ 学习 /docker\_practice.pdf");
FileBody fileBody = new FileBody(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER\_COMPATIBLE);
builder.addPart("file", fileBody); //addPart 上传文件
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
System.out.println(EntityUtils.toString(response.getEntity()));
}
通过 addPart 上传文件
DELETE 申请:
@Test
public void testDelete() throws IOException {
String api = "/api/user/12";
String url = String.format("%s%s", BASE\_URL, api);
HttpDelete httpDelete = new HttpDelete(url);
CloseableHttpResponse response = httpClient.execute(httpDelete);
System.out.println(EntityUtils.toString(response.getEntity()));
}
申请的勾销:
@Test
public void testCancel() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE\_URL, api);
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig); // 设置超时工夫
// 测试连贯的勾销
long begin = System.currentTimeMillis();
CloseableHttpResponse response = httpClient.execute(httpGet);
while (true) {if (System.currentTimeMillis() - begin > 1000) {httpGet.abort();
System.out.println("task canceled");
break;
}
}
System.out.println(EntityUtils.toString(response.getEntity()));
}
调用 abort 办法勾销申请 执行后果:
task canceled
cost 8098 msc
Disconnected from the target VM, address: '127.0.0.1:60549', transport: 'socket'
java.net.SocketException: socket closed...【省略】
OkHttp 应用
应用 OkHttp 发送申请次要分为一下几步骤:
- 创立 OkHttpClient 对象
- 创立 Request 对象
- 将 Request 对象封装为 Call
- 通过 Call 来执行同步或异步申请,调用 execute 办法同步执行,调用 enqueue 办法异步执行
创立连贯:
private OkHttpClient client = new OkHttpClient();
GET 申请:
@Test
public void testGet() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE\_URL, api);
Request request = new Request.Builder()
.url(url)
.get()
.build();
final Call call = client.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}
PUT 申请:
@Test
public void testPut() throws IOException {
String api = "/api/user";
String url = String.format("%s%s", BASE\_URL, api);
// 申请参数
UserVO userVO = UserVO.builder().name("h2t").id(11L).build();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
JSONObject.toJSONString(userVO));
Request request = new Request.Builder()
.url(url)
.put(requestBody)
.build();
final Call call = client.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}
POST 申请:
- 增加对象
@Test
public void testPost() throws IOException {
String api = "/api/user";
String url = String.format("%s%s", BASE\_URL, api);
// 申请参数
JSONObject json = new JSONObject();
json.put("name", "hetiantian");
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), String.valueOf(json));
Request request = new Request.Builder()
.url(url)
.post(requestBody) //post 申请
.build();
final Call call = client.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}
- 上传文件
@Test
public void testUpload() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE\_URL, api);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "docker\_practice.pdf",
RequestBody.create(MediaType.parse("multipart/form-data"),
new File("C:/Users/hetiantian/Desktop/ 学习 /docker\_practice.pdf")))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody) // 默认为 GET 申请,能够不写
.build();
final Call call = client.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}
通过 addFormDataPart 办法模仿表单形式上传文件
DELETE 申请:
@Test
public void testDelete() throws IOException {String url = String.format("%s%s", BASE\_URL, api);
// 申请参数
Request request = new Request.Builder()
.url(url)
.delete()
.build();
final Call call = client.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}
申请的勾销:
@Test
public void testCancelSysnc() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE\_URL, api);
Request request = new Request.Builder()
.url(url)
.get()
.build();
final Call call = client.newCall(request);
Response response = call.execute();
long start = System.currentTimeMillis();
// 测试连贯的勾销
while (true) {
// 1 分钟获取不到后果就勾销申请
if (System.currentTimeMillis() - start > 1000) {call.cancel();
System.out.println("task canceled");
break;
}
}
System.out.println(response.body().string());
}
调用 cancel 办法进行勾销 测试后果:
task canceled
cost 9110 msc
java.net.SocketException: socket closed...【省略】
小结
- OkHttp 应用 build 模式创建对象来的更简洁一些,并且应用. post/.delete/.put/.get 办法示意申请类型,不须要像 HttpClient 创立 HttpGet、HttpPost 等这些办法来创立申请类型
- 依赖包上,如果 HttpClient 须要发送异步申请、实现文件上传,须要额定的引入异步申请依赖
<!--- 文件上传 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.3</version>
</dependency>
<!-- 异步申请 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.5.3</version>
</dependency>
- 申请的勾销,HttpClient 应用 abort 办法,OkHttp 应用 cancel 办法,都挺简略的,如果应用的是异步 client,则在抛出异样时调用勾销申请的办法即可
超时设置
HttpClient 超时设置:在 HttpClient4.3 + 版本以上,超时设置通过 RequestConfig 进行设置
private CloseableHttpClient httpClient = HttpClientBuilder.create().build();
private RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(60 \/* 1000)
.setConnectTimeout(60 \/* 1000).build();
String api = "/api/files/1";
String url = String.format("%s%s", BASE\_URL, api);
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig); // 设置超时工夫
超时工夫是设置在申请类型 HttpGet 上,而不是 HttpClient 上
OkHttp 超时设置:间接在 OkHttp 上进行设置
private OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)// 设置连贯超时工夫
.readTimeout(60, TimeUnit.SECONDS)// 设置读取超时工夫
.build();
小结:如果 client 是单例模式,HttpClient 在设置超时方面来的更灵便,针对不同申请类型设置不同的超时工夫,OkHttp 一旦设置了超时工夫,所有申请类型的超时工夫也就确定
HttpClient 和 OkHttp 性能比拟
测试环境:
- CPU 六核
- 内存 8G
- windows10
每种测试用例都测试五次,排除必然性
client 连贯为单例:
img
client 连贯不为单例:
img
单例模式下,HttpClient 的响应速度要更快一些,单位为毫秒,性能差别相差不大 非单例模式下,OkHttp 的性能更好,HttpClient 创立连贯比拟耗时,因为少数状况下这些资源都会写成单例模式,因而图一的测试后果更具备参考价值
总结
OkHttp 和 HttpClient 在性能和应用上 不分伯仲,依据理论业务抉择即可 最初附:示例代码:https://github.com/TiantianUp…,欢送 fork 与 star/* 良久没有对外输入文章了
img
次要是写的前两篇没有人看,受打击了,急需网友的必定【点赞呀】
END
举荐浏览
太赞了,这个 Java 网站,什么我的项目都有!https://markerhub.com
这个 B 站的 UP 主,讲的 java 真不错!
太赞了!最新版 Java 编程思维能够在线看了!