真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

怎么使用HttpClient和OkHttp

這篇文章主要講解了“怎么使用HttpClient和OkHttp”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“怎么使用HttpClient和OkHttp”吧!

創(chuàng)新互聯(lián)專注于泰和網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供泰和營銷型網(wǎng)站建設(shè),泰和網(wǎng)站制作、泰和網(wǎng)頁設(shè)計(jì)、泰和網(wǎng)站官網(wǎng)定制、微信小程序服務(wù),打造泰和網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供泰和網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。

使用

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

HttpClient使用介紹

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

  •  創(chuàng)建 CloseableHttpClient對(duì)象或CloseableHttpAsyncClient對(duì)象,前者同步,后者為異步

  •  創(chuàng)建Http請求對(duì)象

  •  調(diào)用execute方法執(zhí)行請求,如果是異步請求在執(zhí)行之前需調(diào)用start方法

創(chuàng)建連接:

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調(diào)用execute方法發(fā)送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("h3t").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請求:

添加對(duì)象

@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("h3t2").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()));  }

該請求是一個(gè)創(chuàng)建對(duì)象的請求,需要傳入一個(gè)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/學(xué)習(xí)/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);  //設(shè)置超時(shí)時(shí)間      //測試連接的取消      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()));  }

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

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發(fā)送請求主要分為以下幾步驟:

  •  創(chuàng)建OkHttpClient對(duì)象

  •  創(chuàng)建Request對(duì)象

  •  將Request 對(duì)象封裝為Call

  •  通過Call 來執(zhí)行同步或異步請求,調(diào)用execute方法同步執(zhí)行,調(diào)用enqueue方法異步執(zhí)行

創(chuàng)建連接:

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);      //請求參數(shù)      UserVO userVO = UserVO.builder().name("h3t").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請求:

添加對(duì)象

@Test  public void testPost() throws IOException {      String api = "/api/user";      String url = String.format("%s%s", BASE_URL, api);      //請求參數(shù)      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/學(xué)習(xí)/docker_practice.pdf")))              .build();      Request request = new Request.Builder()              .url(url)              .post(requestBody)  //默認(rèn)為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);    //請求參數(shù)    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分鐘獲取不到結(jié)果就取消請求          if (System.currentTimeMillis() - start > 1000) {              call.cancel();              System.out.println("task canceled");              break;          }      }      System.out.println(response.body().string());  }

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

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

小結(jié)

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

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

          org.apache.httpcomponents       httpmime       4.5.3                org.apache.httpcomponents       httpasyncclient       4.5.3   

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

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

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

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

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);  //設(shè)置超時(shí)時(shí)間

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

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

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

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

小結(jié):

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

HttpClient和OkHttp性能比較

測試環(huán)境:

  •  CPU 六核

  •  內(nèi)存 8G

  •  windows10

每種測試用例都測試五次,排除偶然性

client連接為單例:

怎么使用HttpClient和OkHttp

client連接不為單例:

怎么使用HttpClient和OkHttp

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

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

感謝各位的閱讀,以上就是“怎么使用HttpClient和OkHttp”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)怎么使用HttpClient和OkHttp這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!


當(dāng)前題目:怎么使用HttpClient和OkHttp
鏈接URL:http://weahome.cn/article/gcjpjs.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部