自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

HTTP客戶(hù)端連接,選擇HttpClient還是OkHttp?

開(kāi)發(fā) 后端
根據(jù)關(guān)鍵字httpclient和okhttp的區(qū)別、性能比較進(jìn)行搜索,沒(méi)有找到想要的答案,于是就去overstackflow上看看是不是有人問(wèn)過(guò)這個(gè)問(wèn)題,果然不會(huì)讓你失望的。

寫(xiě)在前面

為什么會(huì)寫(xiě)這篇文章,起因于和朋友的聊天

這又觸及到我的知識(shí)盲區(qū)了,首先來(lái)一波面向百度學(xué)習(xí),直接根據(jù)關(guān)鍵字httpclient和okhttp的區(qū)別、性能比較進(jìn)行搜索,沒(méi)有找到想要的答案,于是就去overstackflow上看看是不是有人問(wèn)過(guò)這個(gè)問(wèn)題,果然不會(huì)讓你失望的

所以從使用、性能、超時(shí)配置方面進(jìn)行比較

使用

HttpClient和OkHttp一般用于調(diào)用其它服務(wù),一般服務(wù)暴露出來(lái)的接口都為http,http常用請(qǐng)求類(lèi)型就為GET、PUT、POST和DELETE,因此主要介紹這些請(qǐng)求類(lèi)型的調(diào)用

HttpClient使用介紹

使用HttpClient發(fā)送請(qǐng)求主要分為以下幾步驟:

  •  創(chuàng)建 CloseableHttpClient對(duì)象或CloseableHttpAsyncClient對(duì)象,前者同步,后者為異步
  •  創(chuàng)建Http請(qǐng)求對(duì)象
  •  調(diào)用execute方法執(zhí)行請(qǐng)求,如果是異步請(qǐng)求在執(zhí)行之前需調(diào)用start方法

創(chuàng)建連接: 

  1. CloseableHttpClient httpClient = HttpClientBuilder.create().build(); 

該連接為同步連接

GET請(qǐng)求: 

  1. @Test  
  2. public void testGet() throws IOException {  
  3.     String api = "/api/files/1" 
  4.     String url = String.format("%s%s", BASE_URL, api);  
  5.     HttpGet httpGet = new HttpGet(url);  
  6.     CloseableHttpResponse response = httpClient.execute(httpGet);  
  7.     System.out.println(EntityUtils.toString(response.getEntity()));  

使用HttpGet表示該連接為GET請(qǐng)求,HttpClient調(diào)用execute方法發(fā)送GET請(qǐng)求

PUT請(qǐng)求: 

  1. @Test  
  2. public void testPut() throws IOException {  
  3.     String api = "/api/user" 
  4.     String url = String.format("%s%s", BASE_URL, api);  
  5.     HttpPut httpPut = new HttpPut(url);  
  6.     UserVO userVO = UserVO.builder().name("h2t").id(16L).build();  
  7.     httpPut.setHeader("Content-Type", "application/json;charset=utf8");  
  8.     httpPut.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8"));  
  9.     CloseableHttpResponse response = httpClient.execute(httpPut);  
  10.     System.out.println(EntityUtils.toString(response.getEntity()));  

POST請(qǐng)求:

添加對(duì)象 

  1. @Test  
  2. public void testPost() throws IOException {  
  3.     String api = "/api/user" 
  4.     String url = String.format("%s%s", BASE_URL, api);  
  5.     HttpPost httpPost = new HttpPost(url);  
  6.     UserVO userVO = UserVO.builder().name("h2t2").build();  
  7.     httpPost.setHeader("Content-Type", "application/json;charset=utf8");  
  8.     httpPost.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8"));  
  9.     CloseableHttpResponse response = httpClient.execute(httpPost);  
  10.     System.out.println(EntityUtils.toString(response.getEntity()));  

該請(qǐng)求是一個(gè)創(chuàng)建對(duì)象的請(qǐng)求,需要傳入一個(gè)json字符串

上傳文件 

  1. @Test  
  2. public void testUpload1() throws IOException {  
  3.     String api = "/api/files/1" 
  4.     String url = String.format("%s%s", BASE_URL, api);  
  5.     HttpPost httpPost = new HttpPost(url); 
  6.      File file = new File("C:/Users/hetiantian/Desktop/學(xué)習(xí)/docker_practice.pdf");  
  7.     FileBody fileBody = new FileBody(file);  
  8.     MultipartEntityBuilder builder = MultipartEntityBuilder.create();  
  9.     builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 
  10.      builder.addPart("file", fileBody);  //addPart上傳文件  
  11.     HttpEntity entity = builder.build();  
  12.     httpPost.setEntity(entity);  
  13.     CloseableHttpResponse response = httpClient.execute(httpPost);  
  14.     System.out.println(EntityUtils.toString(response.getEntity()));  

通過(guò)addPart上傳文件

DELETE請(qǐng)求: 

  1. @Test  
  2. public void testDelete() throws IOException {  
  3.     String api = "/api/user/12" 
  4.     String url = String.format("%s%s", BASE_URL, api);  
  5.     HttpDelete httpDelete = new HttpDelete(url);  
  6.     CloseableHttpResponse response = httpClient.execute(httpDelete);  
  7.     System.out.println(EntityUtils.toString(response.getEntity()));  

請(qǐng)求的取消: 

  1. @Test  
  2. public void testCancel() throws IOException {  
  3.     String api = "/api/files/1" 
  4.     String url = String.format("%s%s", BASE_URL, api);  
  5.     HttpGet httpGet = new HttpGet(url);  
  6.     httpGet.setConfig(requestConfig);  //設(shè)置超時(shí)時(shí)間  
  7.     //測(cè)試連接的取消  
  8.     long begin = System.currentTimeMillis();  
  9.     CloseableHttpResponse response = httpClient.execute(httpGet);  
  10.     while (true) {  
  11.         if (System.currentTimeMillis() - begin > 1000) {  
  12.           httpGet.abort();  
  13.           System.out.println("task canceled");  
  14.           break;  
  15.       }  
  16.     }  
  17.     System.out.println(EntityUtils.toString(response.getEntity()));  

調(diào)用abort方法取消請(qǐng)求 執(zhí)行結(jié)果: 

  1. task canceled  
  2. cost 8098 msc  
  3. Disconnected from the target VM, address: '127.0.0.1:60549', transport: 'socket'  
  4. java.net.SocketException: socket closed...【省略】 

OkHttp使用

使用OkHttp發(fā)送請(qǐng)求主要分為以下幾步驟:

  •  創(chuàng)建OkHttpClient對(duì)象
  •  創(chuàng)建Request對(duì)象
  •  將Request 對(duì)象封裝為Call
  •  通過(guò)Call 來(lái)執(zhí)行同步或異步請(qǐng)求,調(diào)用execute方法同步執(zhí)行,調(diào)用enqueue方法異步執(zhí)行

創(chuàng)建連接: 

  1. private OkHttpClient client = new OkHttpClient(); 

GET請(qǐng)求: 

  1. @Test  
  2. public void testGet() throws IOException {  
  3.     String api = "/api/files/1" 
  4.     String url = String.format("%s%s", BASE_URL, api);  
  5.     Request request = new Request.Builder()  
  6.             .url(url)  
  7.             .get()   
  8.             .build();  
  9.     final Call call = client.newCall(request);  
  10.     Response response = call.execute();  
  11.     System.out.println(response.body().string());  

PUT請(qǐng)求: 

  1. @Test  
  2. public void testPut() throws IOException {  
  3.     String api = "/api/user" 
  4.     String url = String.format("%s%s", BASE_URL, api);  
  5.     //請(qǐng)求參數(shù)  
  6.     UserVO userVO = UserVO.builder().name("h2t").id(11L).build();  
  7.     RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),  
  8.     JSONObject.toJSONString(userVO));  
  9.     Request request = new Request.Builder()  
  10.             .url(url)  
  11.             .put(requestBody)  
  12.             .build();  
  13.     final Call call = client.newCall(request);  
  14.     Response response = call.execute();  
  15.     System.out.println(response.body().string());  

POST請(qǐng)求:

添加對(duì)象 

  1. @Test  
  2. public void testPost() throws IOException {  
  3.     String api = "/api/user" 
  4.     String url = String.format("%s%s", BASE_URL, api);  
  5.     //請(qǐng)求參數(shù)  
  6.     JSONObject json = new JSONObject();  
  7.     json.put("name", "hetiantian");  
  8.     RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),     String.valueOf(json));  
  9.     Request request = new Request.Builder() 
  10.             .url(url)  
  11.             .post(requestBody) //post請(qǐng)求  
  12.            .build();  
  13.     final Call call = client.newCall(request);  
  14.     Response response = call.execute();  
  15.     System.out.println(response.body().string());  

上傳文件 

  1. @Test  
  2. public void testUpload() throws IOException {  
  3.     String api = "/api/files/1" 
  4.     String url = String.format("%s%s", BASE_URL, api);  
  5.     RequestBody requestBody = new MultipartBody.Builder()  
  6.             .setType(MultipartBody.FORM)  
  7.             .addFormDataPart("file", "docker_practice.pdf",  
  8.                     RequestBody.create(MediaType.parse("multipart/form-data"),  
  9.                             new File("C:/Users/hetiantian/Desktop/學(xué)習(xí)/docker_practice.pdf")))  
  10.             .build();  
  11.     Request request = new Request.Builder()  
  12.             .url(url)  
  13.             .post(requestBody)  //默認(rèn)為GET請(qǐng)求,可以不寫(xiě)  
  14.             .build();  
  15.     final Call call = client.newCall(request);  
  16.     Response response = call.execute();  
  17.     System.out.println(response.body().string());  

通過(guò)addFormDataPart方法模擬表單方式上傳文件

DELETE請(qǐng)求: 

  1. @Test  
  2. public void testDelete() throws IOException {  
  3.   String url = String.format("%s%s", BASE_URL, api);  
  4.   //請(qǐng)求參數(shù)  
  5.   Request request = new Request.Builder()  
  6.           .url(url)  
  7.           .delete()  
  8.           .build();  
  9.   final Call call = client.newCall(request);  
  10.   Response response = call.execute();  
  11.   System.out.println(response.body().string());  

請(qǐng)求的取消: 

  1. @Test  
  2. public void testCancelSysnc() throws IOException {  
  3.     String api = "/api/files/1" 
  4.     String url = String.format("%s%s", BASE_URL, api);  
  5.     Request request = new Request.Builder()  
  6.             .url(url)  
  7.             .get()    
  8.             .build();  
  9.     final Call call = client.newCall(request);  
  10.     Response response = call.execute();  
  11.     long start = System.currentTimeMillis();  
  12.     //測(cè)試連接的取消  
  13.     while (true) {  
  14.          //1分鐘獲取不到結(jié)果就取消請(qǐng)求  
  15.         if (System.currentTimeMillis() - start > 1000) {  
  16.             call.cancel();  
  17.             System.out.println("task canceled");  
  18.             break;  
  19.         }  
  20.     }  
  21.     System.out.println(response.body().string());  

調(diào)用cancel方法進(jìn)行取消 測(cè)試結(jié)果: 

  1. task canceled  
  2. cost 9110 msc  
  3. java.net.SocketException: socket closed...【省略】 

小結(jié)

OkHttp使用build模式創(chuàng)建對(duì)象來(lái)的更簡(jiǎn)潔一些,并且使用.post/.delete/.put/.get方法表示請(qǐng)求類(lèi)型,不需要像HttpClient創(chuàng)建HttpGet、HttpPost等這些方法來(lái)創(chuàng)建請(qǐng)求類(lèi)型

依賴(lài)包上,如果HttpClient需要發(fā)送異步請(qǐng)求、實(shí)現(xiàn)文件上傳,需要額外的引入異步請(qǐng)求依賴(lài) 

  1. <!---文件上傳-->  
  2.  <dependency>  
  3.      <groupId>org.apache.httpcomponents</groupId>  
  4.      <artifactId>httpmime</artifactId>  
  5.      <version>4.5.3</version>  
  6.  </dependency>  
  7.  <!--異步請(qǐng)求-->  
  8.  <dependency>  
  9.      <groupId>org.apache.httpcomponents</groupId>  
  10.      <artifactId>httpasyncclient</artifactId>  
  11.      <version>4.5.3</version>  
  12.  </dependency> 

請(qǐng)求的取消,HttpClient使用abort方法,OkHttp使用cancel方法,都挺簡(jiǎn)單的,如果使用的是異步client,則在拋出異常時(shí)調(diào)用取消請(qǐng)求的方法即可

超時(shí)設(shè)置

HttpClient超時(shí)設(shè)置:

在HttpClient4.3+版本以上,超時(shí)設(shè)置通過(guò)RequestConfig進(jìn)行設(shè)置 

  1. private CloseableHttpClient httpClient = HttpClientBuilder.create().build();  
  2. private RequestConfig requestConfig =  RequestConfig.custom()  
  3.         .setSocketTimeout(60 * 1000)  
  4.         .setConnectTimeout(60 * 1000).build();  
  5. String api = "/api/files/1" 
  6. String url = String.format("%s%s", BASE_URL, api);  
  7. HttpGet httpGet = new HttpGet(url);  
  8. httpGet.setConfig(requestConfig);  //設(shè)置超時(shí)時(shí)間 

超時(shí)時(shí)間是設(shè)置在請(qǐng)求類(lèi)型HttpGet上,而不是HttpClient上

OkHttp超時(shí)設(shè)置:

直接在OkHttp上進(jìn)行設(shè)置 

  1. private OkHttpClient client = new OkHttpClient.Builder()  
  2.         .connectTimeout(60, TimeUnit.SECONDS)//設(shè)置連接超時(shí)時(shí)間  
  3.         .readTimeout(60, TimeUnit.SECONDS)//設(shè)置讀取超時(shí)時(shí)間  
  4.         .build(); 

小結(jié):

如果client是單例模式,HttpClient在設(shè)置超時(shí)方面來(lái)的更靈活,針對(duì)不同請(qǐng)求類(lèi)型設(shè)置不同的超時(shí)時(shí)間,OkHttp一旦設(shè)置了超時(shí)時(shí)間,所有請(qǐng)求類(lèi)型的超時(shí)時(shí)間也就確定

HttpClient和OkHttp性能比較

測(cè)試環(huán)境:

  •  CPU 六核
  •  內(nèi)存 8G
  •  windows10

每種測(cè)試用例都測(cè)試五次,排除偶然性

client連接為單例:

client連接不為單例:

單例模式下,HttpClient的響應(yīng)速度要更快一些,單位為毫秒,性能差異相差不大

非單例模式下,OkHttp的性能更好,HttpClient創(chuàng)建連接比較耗時(shí),因?yàn)槎鄶?shù)情況下這些資源都會(huì)寫(xiě)成單例模式,因此圖一的測(cè)試結(jié)果更具有參考價(jià)值

總結(jié)

OkHttp和HttpClient在性能和使用上不分伯仲,根據(jù)實(shí)際業(yè)務(wù)選擇即可

示例代碼

https://github.com/TiantianUpup/http-call

 

 

責(zé)任編輯:龐桂玉 來(lái)源: Java編程
相關(guān)推薦

2024-05-09 08:30:57

OkHttpHTTP客戶(hù)端

2021-04-22 08:33:00

ForestHTTPAPI框

2011-08-17 10:10:59

2022-03-08 13:46:22

httpClientHTTP前端

2023-10-30 11:28:33

Kubernetes負(fù)載均衡

2013-03-13 10:51:44

瘦客戶(hù)端VDI

2010-02-22 09:03:22

零客戶(hù)端瘦客戶(hù)端VDI終端

2021-10-18 05:00:38

語(yǔ)言GoRequestHTTP

2020-11-17 08:53:07

MySQL數(shù)據(jù)庫(kù)技術(shù)

2012-04-23 09:51:09

2021-08-06 10:37:34

ElasticOpenSearch開(kāi)發(fā)者

2017-05-24 08:58:16

HiveServer界面工具

2021-09-22 15:46:29

虛擬桌面瘦客戶(hù)端胖客戶(hù)端

2024-10-16 08:51:57

2009-08-21 15:36:41

服務(wù)端與客戶(hù)端

2009-08-21 15:54:40

服務(wù)端與客戶(hù)端

2013-03-20 11:01:37

Redis客戶(hù)端連接

2010-05-31 10:11:32

瘦客戶(hù)端

2011-10-26 13:17:05

2011-03-02 14:36:24

Filezilla客戶(hù)端
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)