HTTP客戶端鏈接,選擇HttpClient仍是OkHttp?

寫在前面

爲何會寫這篇文章,原由於和朋友的聊天 java

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

使用

HttpClient和OkHttp通常用於調用其它服務,通常服務暴露出來的接口都爲http,http經常使用請求類型就爲GET、PUT、POST和DELETE,所以主要介紹這些請求類型的調用git

HttpClient使用介紹

使用HttpClient發送請求主要分爲一下幾步驟:github

  • 建立 CloseableHttpClient對象或CloseableHttpAsyncClient對象,前者同步,後者爲異步
  • 建立Http請求對象
  • 調用execute方法執行請求,若是是異步請求在執行以前需調用start方法

建立鏈接:docker

CloseableHttpClient httpClient = HttpClientBuilder.create().build();
複製代碼

該鏈接爲同步鏈接apache

GET請求:json

@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請求windows

PUT請求:api

@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請求:bash

  • 添加對象
    @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請求:app

@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鏈接爲單例:

client鏈接不爲單例:
單例模式下,HttpClient的響應速度要更快一些,單位爲毫秒,性能差別相差不大 非單例模式下,OkHttp的性能更好,HttpClient建立鏈接比較耗時,由於多數狀況下這些資源都會寫成單例模式,所以圖一的測試結果更具備參考價值

總結

OkHttp和HttpClient在性能和使用上不分伯仲,根據實際業務選擇便可
最後附:示例代碼,歡迎forkstar*
很久沒有對外輸出文章了

主要是寫的前兩篇沒有人看,受打擊了,急需網友的確定【 點贊呀
相關文章
相關標籤/搜索