1、有關於HttpClient和OkHttp兩種調用服務的方式區別,我們先到overstackflow上看看大牛們的討論。
所以從使用、性能、超時配置方面進行比較
使用
HttpClient和OkHttp一般用於調用其它服務,一般服務暴露出來的接口都為http,http常用請求類型就為GET、PUT、POST和DELETE,因此主要介紹這些請求類型的調用。
HttpClient使用介紹
使用HttpClient發送請求主要分為以下幾步驟:
-
創建 CloseableHttpClient對象或CloseableHttpAsyncClient對象,前者同步,后者為異步
-
創建Http請求對象
-
調用execute方法執行請求,如果是異步請求在執行之前需調用start方法
創建連接:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
該連接為同步連接
GET請求:
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())); 8 }
使用HttpGet表示該連接為GET請求,HttpClient調用execute方法發送GET請求
PUT請求:
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())); 11 }
POST請求:
添加對象
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())); 11 }
該請求是一個創建對象的請求,需要傳入一個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/學習/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())); 15 }
通過addPart上傳文件
DELETE請求:
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())); 8 }
請求的取消:
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); //設置超時時間 7 //測試連接的取消 8 9 long begin = System.currentTimeMillis(); 10 CloseableHttpResponse response = httpClient.execute(httpGet); 11 while (true) { 12 if (System.currentTimeMillis() - begin > 1000) { 13 httpGet.abort(); 14 System.out.println("task canceled"); 15 break; 16 } 17 } 18 19 System.out.println(EntityUtils.toString(response.getEntity())); 20 }
調用abort方法取消請求 執行結果:
1 task canceled 2 cost 8098 msc 3 Disconnected from the target VM, address: '127.0.0.1:60549', transport: 'socket' 4 5 java.net.SocketException: socket closed...【省略】
OkHttp使用
使用OkHttp發送請求主要分為以下幾步驟:
-
創建OkHttpClient對象
-
創建Request對象
-
將Request 對象封裝為Call
-
通過Call 來執行同步或異步請求,調用execute方法同步執行,調用enqueue方法異步執行
創建連接:
private OkHttpClient client = new OkHttpClient();
GET請求:
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()); 12 }
PUT請求:
1 @Test 2 public void testPut() throws IOException { 3 String api = "/api/user"; 4 String url = String.format("%s%s", BASE_URL, api); 5 //請求參數 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()); 16 }
POST請求:
添加對象
1 @Test 2 public void testPost() throws IOException { 3 String api = "/api/user"; 4 String url = String.format("%s%s", BASE_URL, api); 5 //請求參數 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請求 12 .build(); 13 final Call call = client.newCall(request); 14 Response response = call.execute(); 15 System.out.println(response.body().string()); 16 }
上傳文件
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/學習/docker_practice.pdf"))) 10 .build(); 11 Request request = new Request.Builder() 12 .url(url) 13 .post(requestBody) //默認為GET請求,可以不寫 14 .build(); 15 final Call call = client.newCall(request); 16 Response response = call.execute(); 17 System.out.println(response.body().string()); 18 }
通過addFormDataPart方法模擬表單方式上傳文件DELETE請求:
1 @Test 2 public void testDelete() throws IOException { 3 String url = String.format("%s%s", BASE_URL, api); 4 //請求參數 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()); 12 }
請求的取消:
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 //測試連接的取消 13 while (true) { 14 //1分鍾獲取不到結果就取消請求 15 if (System.currentTimeMillis() - start > 1000) { 16 call.cancel(); 17 System.out.println("task canceled"); 18 break; 19 } 20 } 21 22 System.out.println(response.body().string()); 23 }
調用cancel方法進行取消 測試結果:
1 task canceled 2 cost 9110 msc 3 4 java.net.SocketException: socket closed...【省略】
小結
OkHttp使用build模式創建對象來的更簡潔一些,並且使用.post/.delete/.put/.get方法表示請求類型,不需要像HttpClient創建HttpGet、HttpPost等這些方法來創建請求類型
依賴包上,如果HttpClient需要發送異步請求、實現文件上傳,需要額外的引入異步請求依賴
1 <!---文件上傳--> 2 <dependency> 3 <groupId>org.apache.httpcomponents</groupId> 4 <artifactId>httpmime</artifactId> 5 <version>4.5.3</version> 6 </dependency> 7 <!--異步請求--> 8 <dependency> 9 <groupId>org.apache.httpcomponents</groupId> 10 <artifactId>httpasyncclient</artifactId> 11 <version>4.5.3</version> 12 </dependency>
請求的取消,HttpClient使用abort方法,OkHttp使用cancel方法,都挺簡單的,如果使用的是異步client,則在拋出異常時調用取消請求的方法即可
超時設置
HttpClient超時設置:
在HttpClient4.3+版本以上,超時設置通過RequestConfig進行設置
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); //設置超時時間
超時時間是設置在請求類型HttpGet上,而不是HttpClient上
OkHttp超時設置:
直接在OkHttp上進行設置
1 private OkHttpClient client = new OkHttpClient.Builder() 2 .connectTimeout(60, TimeUnit.SECONDS)//設置連接超時時間 3 .readTimeout(60, TimeUnit.SECONDS)//設置讀取超時時間 4 .build();
小結:
如果client是單例模式,HttpClient在設置超時方面來的更靈活,針對不同請求類型設置不同的超時時間,OkHttp一旦設置了超時時間,所有請求類型的超時時間也就確定
HttpClient和OkHttp性能比較
測試環境:
-
CPU 六核
-
內存 8G
-
windows10
每種測試用例都測試五次,排除偶然性
client連接為單例:
client連接不為單例:
單例模式下,HttpClient的響應速度要更快一些,單位為毫秒,性能差異相差不大
非單例模式下,OkHttp的性能更好,HttpClient創建連接比較耗時,因為多數情況下這些資源都會寫成單例模式,因此圖一的測試結果更具有參考價值
總結
OkHttp和HttpClient在性能和使用上不分伯仲,根據實際業務選擇即可