為什么會寫這篇文章,起因於和朋友的聊天

這又觸及到我的知識盲區了,首先來一波面向百度學習,直接根據關鍵字httpclient和okhttp的區別、性能比較進行搜索,沒有找到想要的答案,於是就去overstackflow上看看是不是有人問過這個問題,果然不會讓你失望的

所以從使用、性能、超時配置方面進行比較
使用
HttpClient和OkHttp一般用於調用其它服務,一般服務暴露出來的接口都為http,http常用請求類型就為GET、PUT、POST和DELETE,因此主要介紹這些請求類型的調用
HttpClient使用介紹
使用HttpClient發送請求主要分為以下幾步驟:
- 創建 CloseableHttpClient對象或CloseableHttpAsyncClient對象,前者同步,后者為異步
- 創建Http請求對象
- 調用execute方法執行請求,如果是異步請求在執行之前需調用start方法
創建連接:
CloseableHttpClienthttpClient=HttpClientBuilder.create().build();
該連接為同步連接
GET請求:
@TestpublicvoidtestGet()throwsIOException{Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);HttpGethttpGet=newHttpGet(url);CloseableHttpResponseresponse=httpClient.execute(httpGet);System.out.println(EntityUtils.toString(response.getEntity()));}
使用HttpGet表示該連接為GET請求,HttpClient調用execute方法發送GET請求
PUT請求:
@TestpublicvoidtestPut()throwsIOException{Stringapi="/api/user";Stringurl=String.format("%s%s",BASE_URL,api);HttpPuthttpPut=newHttpPut(url);UserVOuserVO=UserVO.builder().name("h2t").id(16L).build();httpPut.setHeader("Content-Type","application/json;charset=utf8");httpPut.setEntity(newStringEntity(JSONObject.toJSONString(userVO),"UTF-8"));CloseableHttpResponseresponse=httpClient.execute(httpPut);System.out.println(EntityUtils.toString(response.getEntity()));}
POST請求:
添加對象
@TestpublicvoidtestPost()throwsIOException{Stringapi="/api/user";Stringurl=String.format("%s%s",BASE_URL,api);HttpPosthttpPost=newHttpPost(url);UserVOuserVO=UserVO.builder().name("h2t2").build();httpPost.setHeader("Content-Type","application/json;charset=utf8");httpPost.setEntity(newStringEntity(JSONObject.toJSONString(userVO),"UTF-8"));CloseableHttpResponseresponse=httpClient.execute(httpPost);System.out.println(EntityUtils.toString(response.getEntity()));}
該請求是一個創建對象的請求,需要傳入一個json字符串
上傳文件
@TestpublicvoidtestUpload1()throwsIOException{Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);HttpPosthttpPost=newHttpPost(url);Filefile=newFile("C:/Users/hetiantian/Desktop/學習/docker_practice.pdf");FileBodyfileBody=newFileBody(file);MultipartEntityBuilderbuilder=MultipartEntityBuilder.create();builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);builder.addPart("file",fileBody);//addPart上傳文件HttpEntityentity=builder.build();httpPost.setEntity(entity);CloseableHttpResponseresponse=httpClient.execute(httpPost);System.out.println(EntityUtils.toString(response.getEntity()));}
通過addPart上傳文件
DELETE請求:
@TestpublicvoidtestDelete()throwsIOException{Stringapi="/api/user/12";Stringurl=String.format("%s%s",BASE_URL,api);HttpDeletehttpDelete=newHttpDelete(url);CloseableHttpResponseresponse=httpClient.execute(httpDelete);System.out.println(EntityUtils.toString(response.getEntity()));}
請求的取消:
@TestpublicvoidtestCancel()throwsIOException{Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);HttpGethttpGet=newHttpGet(url);httpGet.setConfig(requestConfig);//設置超時時間//測試連接的取消longbegin=System.currentTimeMillis();CloseableHttpResponseresponse=httpClient.execute(httpGet);while(true){if(System.currentTimeMillis()-begin>1000){httpGet.abort();System.out.println("taskcanceled");break;}}System.out.println(EntityUtils.toString(response.getEntity()));}
調用abort方法取消請求 執行結果:
taskcanceledcost8098mscDisconnectedfromthetargetVM,address:'127.0.0.1:60549',transport:'socket'java.net.SocketException:socketclosed...【省略】
OkHttp使用
使用OkHttp發送請求主要分為以下幾步驟:
- 創建OkHttpClient對象
- 創建Request對象
- 將Request 對象封裝為Call
- 通過Call 來執行同步或異步請求,調用execute方法同步執行,調用enqueue方法異步執行
創建連接:
privateOkHttpClientclient=newOkHttpClient();
GET請求:
@TestpublicvoidtestGet()throwsIOException{Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);Requestrequest=newRequest.Builder().url(url).get().build();finalCallcall=client.newCall(request);Responseresponse=call.execute();System.out.println(response.body().string());}
PUT請求:
@TestpublicvoidtestPut()throwsIOException{Stringapi="/api/user";Stringurl=String.format("%s%s",BASE_URL,api);//請求參數UserVOuserVO=UserVO.builder().name("h2t").id(11L).build();RequestBodyrequestBody=RequestBody.create(MediaType.parse("application/json;charset=utf-8"),JSONObject.toJSONString(userVO));Requestrequest=newRequest.Builder().url(url).put(requestBody).build();finalCallcall=client.newCall(request);Responseresponse=call.execute();System.out.println(response.body().string());}
POST請求:
添加對象
@TestpublicvoidtestPost()throwsIOException{Stringapi="/api/user";Stringurl=String.format("%s%s",BASE_URL,api);//請求參數JSONObjectjson=newJSONObject();json.put("name","hetiantian");RequestBodyrequestBody=RequestBody.create(MediaType.parse("application/json;charset=utf-8"),String.valueOf(json));Requestrequest=newRequest.Builder().url(url).post(requestBody)//post請求.build();finalCallcall=client.newCall(request);Responseresponse=call.execute();System.out.println(response.body().string());}
上傳文件
@TestpublicvoidtestUpload()throwsIOException{Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);RequestBodyrequestBody=newMultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file","docker_practice.pdf",RequestBody.create(MediaType.parse("multipart/form-data"),newFile("C:/Users/hetiantian/Desktop/學習/docker_practice.pdf"))).build();Requestrequest=newRequest.Builder().url(url).post(requestBody)//默認為GET請求,可以不寫.build();finalCallcall=client.newCall(request);Responseresponse=call.execute();System.out.println(response.body().string());}
通過addFormDataPart方法模擬表單方式上傳文件
DELETE請求:
@TestpublicvoidtestDelete()throwsIOException{Stringurl=String.format("%s%s",BASE_URL,api);//請求參數Requestrequest=newRequest.Builder().url(url).delete().build();finalCallcall=client.newCall(request);Responseresponse=call.execute();System.out.println(response.body().string());}
請求的取消:
@TestpublicvoidtestCancelSysnc()throwsIOException{Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);Requestrequest=newRequest.Builder().url(url).get().build();finalCallcall=client.newCall(request);Responseresponse=call.execute();longstart=System.currentTimeMillis();//測試連接的取消while(true){//1分鍾獲取不到結果就取消請求if(System.currentTimeMillis()-start>1000){call.cancel();System.out.println("taskcanceled");break;}}System.out.println(response.body().string());}
調用cancel方法進行取消 測試結果:
taskcanceledcost9110mscjava.net.SocketException:socketclosed...【省略】
小結
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進行設置
privateCloseableHttpClienthttpClient=HttpClientBuilder.create().build();privateRequestConfigrequestConfig=RequestConfig.custom().setSocketTimeout(60*1000).setConnectTimeout(60*1000).build();Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);HttpGethttpGet=newHttpGet(url);httpGet.setConfig(requestConfig);//設置超時時間
超時時間是設置在請求類型HttpGet上,而不是HttpClient上
OkHttp超時設置:
直接在OkHttp上進行設置
privateOkHttpClientclient=newOkHttpClient.Builder().connectTimeout(60,TimeUnit.SECONDS)//設置連接超時時間.readTimeout(60,TimeUnit.SECONDS)//設置讀取超時時間.build();
小結:
如果client是單例模式,HttpClient在設置超時方面來的更靈活,針對不同請求類型設置不同的超時時間,OkHttp一旦設置了超時時間,所有請求類型的超時時間也就確定
HttpClient和OkHttp性能比較
測試環境:
- CPU 六核
- 內存 8G
- windows10
每種測試用例都測試五次,排除偶然性
client連接為單例:

client連接不為單例:

單例模式下,HttpClient的響應速度要更快一些,單位為毫秒,性能差異相差不大
非單例模式下,OkHttp的性能更好,HttpClient創建連接比較耗時,因為多數情況下這些資源都會寫成單例模式,因此圖一的測試結果更具有參考價值
總結
OkHttp和HttpClient在性能和使用上不分伯仲,根據實際業務選擇即可