HttpClient詳解

        HTTP 協議可能是現在 Internet 上使用得最多、最重要的協議了,越來越多的 Java 應用程序需要直接通過 HTTP 協議來訪問網絡資源。雖然在 JDK 的 java net包中已經提供了訪問 HTTP 協議的基本功能,但是對於大部分應用程序來說,JDK 庫本身提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本和建議。

        HTTP和瀏覽器有點像,但卻不是瀏覽器。很多人覺得既然HttpClient是一個HTTP客戶端編程工具,很多人把他當做瀏覽器來理解,但是其實HttpClient不是瀏覽器,它是一個HTTP通信庫,因此它只提供一個通用瀏覽器應用程序所期望的功能子集,最根本的區別是HttpClient中沒有用戶界面,瀏覽器需要一個渲染引擎來顯示頁面,並解釋用戶輸入,例如鼠標點擊顯示頁面上的某處,有一個佈局引擎,計算如何顯示HTML頁面,包括級聯樣式表和圖像。javascript解釋器運行嵌入HTML頁面或從HTML頁面引用的javascript代碼。來自用戶界面的事件被傳遞到javascript解釋器進行處理。除此之外,還有用於插件的接口,可以處理Applet,嵌入式媒體對象(如pdf文件,Quicktime電影和Flash動畫)或ActiveX控件(可以執行任何操作)。HttpClient只能以編程的方式通過其API用於傳輸和接受HTTP消息。

HttpClient的主要功能:

  • 實現了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
  • 支持 HTTPS 協議
  • 支持代理服務器(Nginx等)等
  • 支持自動(跳轉)轉向
  • ……

進入正題


環境說明:Eclipse、JDK1.8、SpringBoot

準備環節

第一步:在pom.xml中引入HttpClient的依賴

第二步:引入fastjson依賴

注:本人引入此依賴的目的是,在後續示例中,會用到“將對象轉化爲json字符串的功能”,也可以引其他有此功能的依賴。 

注:SpringBoot的基本依賴配置,這裏就不再多說了。


詳細使用示例

聲明:此示例中,以JAVA發送HttpClient(在test裏面單元測試發送的);也是以JAVA接收的(在controller裏面接收的)。

聲明:下面的代碼,本人親測有效。

GET無參

HttpClient發送示例:

  1. /**
  2. * GET---無參測試
  3. *
  4. * @date 2018年7月13日 下午4:18:50
  5. */
  6. @Test
  7. public void doGetTestOne() {
  8. // 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
  9. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  10. // 創建Get請求
  11. HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerOne");
  12. // 響應模型
  13. CloseableHttpResponse response = null;
  14. try {
  15. // 由客戶端執行(發送)Get請求
  16. response = httpClient.execute(httpGet);
  17. // 從響應模型中獲取響應實體
  18. HttpEntity responseEntity = response.getEntity();
  19. System.out.println("響應狀態爲:" + response.getStatusLine());
  20. if (responseEntity != null) {
  21. System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
  22. System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));
  23. }
  24. } catch (ClientProtocolException e) {
  25. e.printStackTrace();
  26. } catch (ParseException e) {
  27. e.printStackTrace();
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. } finally {
  31. try {
  32. // 釋放資源
  33. if (httpClient != null) {
  34. httpClient.close();
  35. }
  36. if (response != null) {
  37. response.close();
  38. }
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. }

對應接收示例:

GET有參(方式一:直接拼接URL)

HttpClient發送示例:

  1. /**
  2. * GET---有參測試 (方式一:手動在url後面加上參數)
  3. *
  4. * @date 2018年7月13日 下午4:19:23
  5. */
  6. @Test
  7. public void doGetTestWayOne() {
  8. // 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
  9. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  10. // 參數
  11. StringBuffer params = new StringBuffer();
  12. try {
  13. // 字符數據最好encoding以下;這樣一來,某些特殊字符才能傳過去(如:某人的名字就是“&”,不encoding的話,傳不過去)
  14. params.append("name=" + URLEncoder.encode("&", "utf-8"));
  15. params.append("&");
  16. params.append("age=24");
  17. } catch (UnsupportedEncodingException e1) {
  18. e1.printStackTrace();
  19. }
  20. // 創建Get請求
  21. HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerTwo" + "?" + params);
  22. // 響應模型
  23. CloseableHttpResponse response = null;
  24. try {
  25. // 配置信息
  26. RequestConfig requestConfig = RequestConfig.custom()
  27. // 設置連接超時時間(單位毫秒)
  28. .setConnectTimeout(5000)
  29. // 設置請求超時時間(單位毫秒)
  30. .setConnectionRequestTimeout(5000)
  31. // socket讀寫超時時間(單位毫秒)
  32. .setSocketTimeout(5000)
  33. // 設置是否允許重定向(默認爲true)
  34. .setRedirectsEnabled(true).build();
  35. // 將上面的配置信息 運用到這個Get請求裏
  36. httpGet.setConfig(requestConfig);
  37. // 由客戶端執行(發送)Get請求
  38. response = httpClient.execute(httpGet);
  39. // 從響應模型中獲取響應實體
  40. HttpEntity responseEntity = response.getEntity();
  41. System.out.println("響應狀態爲:" + response.getStatusLine());
  42. if (responseEntity != null) {
  43. System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
  44. System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));
  45. }
  46. } catch (ClientProtocolException e) {
  47. e.printStackTrace();
  48. } catch (ParseException e) {
  49. e.printStackTrace();
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. } finally {
  53. try {
  54. // 釋放資源
  55. if (httpClient != null) {
  56. httpClient.close();
  57. }
  58. if (response != null) {
  59. response.close();
  60. }
  61. } catch (IOException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. }

對應接收示例:

GET有參(方式二:使用URI獲得HttpGet)

HttpClient發送示例:

  1. /**
  2. * GET---有參測試 (方式二:將參數放入鍵值對類中,再放入URI中,從而通過URI得到HttpGet實例)
  3. *
  4. * @date 2018年7月13日 下午4:19:23
  5. */
  6. @Test
  7. public void doGetTestWayTwo() {
  8. // 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
  9. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  10. // 參數
  11. URI uri = null;
  12. try {
  13. // 將參數放入鍵值對類NameValuePair中,再放入集合中
  14. List<NameValuePair> params = new ArrayList<>();
  15. params.add(new BasicNameValuePair("name", "&"));
  16. params.add(new BasicNameValuePair("age", "18"));
  17. // 設置uri信息,並將參數集合放入uri;
  18. // 注:這裏也支持一個鍵值對一個鍵值對地往裏面放setParameter(String key, String value)
  19. uri = new URIBuilder().setScheme("http").setHost("localhost")
  20. .setPort(12345).setPath("/doGetControllerTwo")
  21. .setParameters(params).build();
  22. } catch (URISyntaxException e1) {
  23. e1.printStackTrace();
  24. }
  25. // 創建Get請求
  26. HttpGet httpGet = new HttpGet(uri);
  27. // 響應模型
  28. CloseableHttpResponse response = null;
  29. try {
  30. // 配置信息
  31. RequestConfig requestConfig = RequestConfig.custom()
  32. // 設置連接超時時間(單位毫秒)
  33. .setConnectTimeout(5000)
  34. // 設置請求超時時間(單位毫秒)
  35. .setConnectionRequestTimeout(5000)
  36. // socket讀寫超時時間(單位毫秒)
  37. .setSocketTimeout(5000)
  38. // 設置是否允許重定向(默認爲true)
  39. .setRedirectsEnabled(true).build();
  40. // 將上面的配置信息 運用到這個Get請求裏
  41. httpGet.setConfig(requestConfig);
  42. // 由客戶端執行(發送)Get請求
  43. response = httpClient.execute(httpGet);
  44. // 從響應模型中獲取響應實體
  45. HttpEntity responseEntity = response.getEntity();
  46. System.out.println("響應狀態爲:" + response.getStatusLine());
  47. if (responseEntity != null) {
  48. System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
  49. System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));
  50. }
  51. } catch (ClientProtocolException e) {
  52. e.printStackTrace();
  53. } catch (ParseException e) {
  54. e.printStackTrace();
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. } finally {
  58. try {
  59. // 釋放資源
  60. if (httpClient != null) {
  61. httpClient.close();
  62. }
  63. if (response != null) {
  64. response.close();
  65. }
  66. } catch (IOException e) {
  67. e.printStackTrace();
  68. }
  69. }
  70. }

對應接收示例:

POST無參

HttpClient發送示例:

  1. /**
  2. * POST---無參測試
  3. *
  4. * @date 2018年7月13日 下午4:18:50
  5. */
  6. @Test
  7. public void doPostTestOne() {
  8. // 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
  9. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  10. // 創建Post請求
  11. HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerOne");
  12. // 響應模型
  13. CloseableHttpResponse response = null;
  14. try {
  15. // 由客戶端執行(發送)Post請求
  16. response = httpClient.execute(httpPost);
  17. // 從響應模型中獲取響應實體
  18. HttpEntity responseEntity = response.getEntity();
  19. System.out.println("響應狀態爲:" + response.getStatusLine());
  20. if (responseEntity != null) {
  21. System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
  22. System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));
  23. }
  24. } catch (ClientProtocolException e) {
  25. e.printStackTrace();
  26. } catch (ParseException e) {
  27. e.printStackTrace();
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. } finally {
  31. try {
  32. // 釋放資源
  33. if (httpClient != null) {
  34. httpClient.close();
  35. }
  36. if (response != null) {
  37. response.close();
  38. }
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. }

對應接收示例:

POST有參(普通參數)

注:POST傳遞普通參數時,方式與GET一樣即可,這裏以直接在url後綴上參數的方式示例。

HttpClient發送示例:

  1. /**
  2. * POST---有參測試(普通參數)
  3. *
  4. * @date 2018年7月13日 下午4:18:50
  5. */
  6. @Test
  7. public void doPostTestFour() {
  8. // 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
  9. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  10. // 參數
  11. StringBuffer params = new StringBuffer();
  12. try {
  13. // 字符數據最好encoding以下;這樣一來,某些特殊字符才能傳過去(如:某人的名字就是“&”,不encoding的話,傳不過去)
  14. params.append("name=" + URLEncoder.encode("&", "utf-8"));
  15. params.append("&");
  16. params.append("age=24");
  17. } catch (UnsupportedEncodingException e1) {
  18. e1.printStackTrace();
  19. }
  20. // 創建Post請求
  21. HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerFour" + "?" + params);
  22. // 設置ContentType(注:如果只是傳普通參數的話,ContentType不一定非要用application/json)
  23. httpPost.setHeader("Content-Type", "application/json;charset=utf8");
  24. // 響應模型
  25. CloseableHttpResponse response = null;
  26. try {
  27. // 由客戶端執行(發送)Post請求
  28. response = httpClient.execute(httpPost);
  29. // 從響應模型中獲取響應實體
  30. HttpEntity responseEntity = response.getEntity();
  31. System.out.println("響應狀態爲:" + response.getStatusLine());
  32. if (responseEntity != null) {
  33. System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
  34. System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));
  35. }
  36. } catch (ClientProtocolException e) {
  37. e.printStackTrace();
  38. } catch (ParseException e) {
  39. e.printStackTrace();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. } finally {
  43. try {
  44. // 釋放資源
  45. if (httpClient != null) {
  46. httpClient.close();
  47. }
  48. if (response != null) {
  49. response.close();
  50. }
  51. } catch (IOException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. }

對應接收示例:

POST有參(對象參數)

先給出User類

HttpClient發送示例:

  1. /**
  2. * POST---有參測試(對象參數)
  3. *
  4. * @date 2018年7月13日 下午4:18:50
  5. */
  6. @Test
  7. public void doPostTestTwo() {
  8. // 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
  9. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  10. // 創建Post請求
  11. HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerTwo");
  12. User user = new User();
  13. user.setName("潘曉婷");
  14. user.setAge(18);
  15. user.setGender("女");
  16. user.setMotto("姿勢要優雅~");
  17. // 我這裏利用阿里的fastjson,將Object轉換爲json字符串;
  18. // (需要導入com.alibaba.fastjson.JSON包)
  19. String jsonString = JSON.toJSONString(user);
  20. StringEntity entity = new StringEntity(jsonString, "UTF-8");
  21. // post請求是將參數放在請求體裏面傳過去的;這裏將entity放入post請求體中
  22. httpPost.setEntity(entity);
  23. httpPost.setHeader("Content-Type", "application/json;charset=utf8");
  24. // 響應模型
  25. CloseableHttpResponse response = null;
  26. try {
  27. // 由客戶端執行(發送)Post請求
  28. response = httpClient.execute(httpPost);
  29. // 從響應模型中獲取響應實體
  30. HttpEntity responseEntity = response.getEntity();
  31. System.out.println("響應狀態爲:" + response.getStatusLine());
  32. if (responseEntity != null) {
  33. System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
  34. System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));
  35. }
  36. } catch (ClientProtocolException e) {
  37. e.printStackTrace();
  38. } catch (ParseException e) {
  39. e.printStackTrace();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. } finally {
  43. try {
  44. // 釋放資源
  45. if (httpClient != null) {
  46. httpClient.close();
  47. }
  48. if (response != null) {
  49. response.close();
  50. }
  51. } catch (IOException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. }

對應接收示例:

POST有參(普通參數 + 對象參數)

注:POST傳遞普通參數時,方式與GET一樣即可,這裏以通過URI獲得HttpPost的方式爲例。

先給出User類:

HttpClient發送示例:

  1. /**
  2. * POST---有參測試(普通參數 + 對象參數)
  3. *
  4. * @date 2018年7月13日 下午4:18:50
  5. */
  6. @Test
  7. public void doPostTestThree() {
  8. // 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
  9. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  10. // 創建Post請求
  11. // 參數
  12. URI uri = null;
  13. try {
  14. // 將參數放入鍵值對類NameValuePair中,再放入集合中
  15. List<NameValuePair> params = new ArrayList<>();
  16. params.add(new BasicNameValuePair("flag", "4"));
  17. params.add(new BasicNameValuePair("meaning", "這是什麼鬼?"));
  18. // 設置uri信息,並將參數集合放入uri;
  19. // 注:這裏也支持一個鍵值對一個鍵值對地往裏面放setParameter(String key, String value)
  20. uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(12345)
  21. .setPath("/doPostControllerThree").setParameters(params).build();
  22. } catch (URISyntaxException e1) {
  23. e1.printStackTrace();
  24. }
  25. HttpPost httpPost = new HttpPost(uri);
  26. // HttpPost httpPost = new
  27. // HttpPost("http://localhost:12345/doPostControllerThree1");
  28. // 創建user參數
  29. User user = new User();
  30. user.setName("潘曉婷");
  31. user.setAge(18);
  32. user.setGender("女");
  33. user.setMotto("姿勢要優雅~");
  34. // 將user對象轉換爲json字符串,並放入entity中
  35. StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");
  36. // post請求是將參數放在請求體裏面傳過去的;這裏將entity放入post請求體中
  37. httpPost.setEntity(entity);
  38. httpPost.setHeader("Content-Type", "application/json;charset=utf8");
  39. // 響應模型
  40. CloseableHttpResponse response = null;
  41. try {
  42. // 由客戶端執行(發送)Post請求
  43. response = httpClient.execute(httpPost);
  44. // 從響應模型中獲取響應實體
  45. HttpEntity responseEntity = response.getEntity();
  46. System.out.println("響應狀態爲:" + response.getStatusLine());
  47. if (responseEntity != null) {
  48. System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
  49. System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));
  50. }
  51. } catch (ClientProtocolException e) {
  52. e.printStackTrace();
  53. } catch (ParseException e) {
  54. e.printStackTrace();
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. } finally {
  58. try {
  59. // 釋放資源
  60. if (httpClient != null) {
  61. httpClient.close();
  62. }
  63. if (response != null) {
  64. response.close();
  65. }
  66. } catch (IOException e) {
  67. e.printStackTrace();
  68. }
  69. }
  70. }

對應接收示例:


對評論區關注度較高的問題進行相關補充

提示:如果想要知道完整的具體的代碼及測試細節,可去下面給的項目代碼託管鏈接,將項目clone下來
           進行觀察。如果需要運行測試,可以先啓動該SpringBoot項目,然後再運行相關test方法,進行
           測試。

解決響應亂碼問題(示例)

進行HTTPS請求並進行(或不進行)證書校驗(示例)

使用示例:

相關方法詳情(非完美封裝):

  1. /**
  2. * 根據是否是https請求,獲取HttpClient客戶端
  3. *
  4. * TODO 本人這裏沒有進行完美封裝。對於 校不校驗校驗證書的選擇,本人這裏是寫死
  5. * 在代碼裏面的,你們再使用時,可以靈活二次封裝。
  6. *
  7. * 提示: 此工具類的封裝、相關客戶端、服務端證書的生成,可參考我的這篇博客:
  8. * <linked>https://blog.csdn.net/justry_deng/article/details/91569132</linked>
  9. *
  10. *
  11. * @param isHttps 是否是HTTPS請求
  12. *
  13. * @return HttpClient實例
  14. * @date 2019/9/18 17:57
  15. */
  16. private CloseableHttpClient getHttpClient(boolean isHttps) {
  17. CloseableHttpClient httpClient;
  18. if (isHttps) {
  19. SSLConnectionSocketFactory sslSocketFactory;
  20. try {
  21. /// 如果不作證書校驗的話
  22. sslSocketFactory = getSocketFactory(false, null, null);
  23. /// 如果需要證書檢驗的話
  24. // 證書
  25. //InputStream ca = this.getClass().getClassLoader().getResourceAsStream("client/ds.crt");
  26. // 證書的別名,即:key。 注:cAalias只需要保證唯一即可,不過推薦使用生成keystore時使用的別名。
  27. // String cAalias = System.currentTimeMillis() + "" + new SecureRandom().nextInt(1000);
  28. //sslSocketFactory = getSocketFactory(true, ca, cAalias);
  29. } catch (Exception e) {
  30. throw new RuntimeException(e);
  31. }
  32. httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
  33. return httpClient;
  34. }
  35. httpClient = HttpClientBuilder.create().build();
  36. return httpClient;
  37. }
  38. /**
  39. * HTTPS輔助方法, 爲HTTPS請求 創建SSLSocketFactory實例、TrustManager實例
  40. *
  41. * @param needVerifyCa
  42. * 是否需要檢驗CA證書(即:是否需要檢驗服務器的身份)
  43. * @param caInputStream
  44. * CA證書。(若不需要檢驗證書,那麼此處傳null即可)
  45. * @param cAalias
  46. * 別名。(若不需要檢驗證書,那麼此處傳null即可)
  47. * 注意:別名應該是唯一的, 別名不要和其他的別名一樣,否者會覆蓋之前的相同別名的證書信息。別名即key-value中的key。
  48. *
  49. * @return SSLConnectionSocketFactory實例
  50. * @throws NoSuchAlgorithmException
  51. * 異常信息
  52. * @throws CertificateException
  53. * 異常信息
  54. * @throws KeyStoreException
  55. * 異常信息
  56. * @throws IOException
  57. * 異常信息
  58. * @throws KeyManagementException
  59. * 異常信息
  60. * @date 2019/6/11 19:52
  61. */
  62. private static SSLConnectionSocketFactory getSocketFactory(boolean needVerifyCa, InputStream caInputStream, String cAalias)
  63. throws CertificateException, NoSuchAlgorithmException, KeyStoreException,
  64. IOException, KeyManagementException {
  65. X509TrustManager x509TrustManager;
  66. // https請求,需要校驗證書
  67. if (needVerifyCa) {
  68. KeyStore keyStore = getKeyStore(caInputStream, cAalias);
  69. TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  70. trustManagerFactory.init(keyStore);
  71. TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  72. if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
  73. throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
  74. }
  75. x509TrustManager = (X509TrustManager) trustManagers[0];
  76. // 這裏傳TLS或SSL其實都可以的
  77. SSLContext sslContext = SSLContext.getInstance("TLS");
  78. sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom());
  79. return new SSLConnectionSocketFactory(sslContext);
  80. }
  81. // https請求,不作證書校驗
  82. x509TrustManager = new X509TrustManager() {
  83. @Override
  84. public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
  85. }
  86. @Override
  87. public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
  88. // 不驗證
  89. }
  90. @Override
  91. public X509Certificate[] getAcceptedIssuers() {
  92. return new X509Certificate[0];
  93. }
  94. };
  95. SSLContext sslContext = SSLContext.getInstance("TLS");
  96. sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom());
  97. return new SSLConnectionSocketFactory(sslContext);
  98. }
  99. /**
  100. * 獲取(密鑰及證書)倉庫
  101. * 注:該倉庫用於存放 密鑰以及證書
  102. *
  103. * @param caInputStream
  104. * CA證書(此證書應由要訪問的服務端提供)
  105. * @param cAalias
  106. * 別名
  107. * 注意:別名應該是唯一的, 別名不要和其他的別名一樣,否者會覆蓋之前的相同別名的證書信息。別名即key-value中的key。
  108. * @return 密鑰、證書 倉庫
  109. * @throws KeyStoreException 異常信息
  110. * @throws CertificateException 異常信息
  111. * @throws IOException 異常信息
  112. * @throws NoSuchAlgorithmException 異常信息
  113. * @date 2019/6/11 18:48
  114. */
  115. private static KeyStore getKeyStore(InputStream caInputStream, String cAalias)
  116. throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
  117. // 證書工廠
  118. CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  119. // 祕鑰倉庫
  120. KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
  121. keyStore.load(null);
  122. keyStore.setCertificateEntry(cAalias, certificateFactory.generateCertificate(caInputStream));
  123. return keyStore;
  124. }

application/x-www-form-urlencoded表單請求(示例)

發送文件(示例)

準備工作:

       如果想要靈活方便的傳輸文件的話,除了引入org.apache.httpcomponents基本的httpclient依賴外再額外引入org.apache.httpcomponents的httpmime依賴。
P.S.:即便不引入httpmime依賴,也是能傳輸文件的,不過功能不夠強大。

在pom.xml中額外引入:

  1. <!--
  2. 如果需要靈活的傳輸文件,引入次依賴後會更加方便
  3. -->
  4. <dependency>
  5. <groupId>org.apache.httpcomponents</groupId>
  6. <artifactId>httpmime</artifactId>
  7. <version>4.5.5</version>
  8. </dependency>

發送端是這樣的:

  1. /**
  2. *
  3. * 發送文件
  4. *
  5. * multipart/form-data傳遞文件(及相關信息)
  6. *
  7. * 注:如果想要靈活方便的傳輸文件的話,
  8. * 除了引入org.apache.httpcomponents基本的httpclient依賴外
  9. * 再額外引入org.apache.httpcomponents的httpmime依賴。
  10. * 追注:即便不引入httpmime依賴,也是能傳輸文件的,不過功能不夠強大。
  11. *
  12. */
  13. @Test
  14. public void test4() {
  15. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  16. HttpPost httpPost = new HttpPost("http://localhost:12345/file");
  17. CloseableHttpResponse response = null;
  18. try {
  19. MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
  20. // 第一個文件
  21. String filesKey = "files";
  22. File file1 = new File("C:\\Users\\JustryDeng\\Desktop\\back.jpg");
  23. multipartEntityBuilder.addBinaryBody(filesKey, file1);
  24. // 第二個文件(多個文件的話,使用可一個key就行,後端用數組或集合進行接收即可)
  25. File file2 = new File("C:\\Users\\JustryDeng\\Desktop\\頭像.jpg");
  26. // 防止服務端收到的文件名亂碼。 我們這裏可以先將文件名URLEncode,然後服務端拿到文件名時在URLDecode。就能避免亂碼問題。
  27. // 文件名其實是放在請求頭的Content-Disposition裏面進行傳輸的,如其值爲form-data; name="files"; filename="頭像.jpg"
  28. multipartEntityBuilder.addBinaryBody(filesKey, file2, ContentType.DEFAULT_BINARY, URLEncoder.encode(file2.getName(), "utf-8"));
  29. // 其它參數(注:自定義contentType,設置UTF-8是爲了防止服務端拿到的參數出現亂碼)
  30. ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
  31. multipartEntityBuilder.addTextBody("name", "鄧沙利文", contentType);
  32. multipartEntityBuilder.addTextBody("age", "25", contentType);
  33. HttpEntity httpEntity = multipartEntityBuilder.build();
  34. httpPost.setEntity(httpEntity);
  35. response = httpClient.execute(httpPost);
  36. HttpEntity responseEntity = response.getEntity();
  37. System.out.println("HTTPS響應狀態爲:" + response.getStatusLine());
  38. if (responseEntity != null) {
  39. System.out.println("HTTPS響應內容長度爲:" + responseEntity.getContentLength());
  40. // 主動設置編碼,來防止響應亂碼
  41. String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
  42. System.out.println("HTTPS響應內容爲:" + responseStr);
  43. }
  44. } catch (ParseException | IOException e) {
  45. e.printStackTrace();
  46. } finally {
  47. try {
  48. // 釋放資源
  49. if (httpClient != null) {
  50. httpClient.close();
  51. }
  52. if (response != null) {
  53. response.close();
  54. }
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. }

接收端是這樣的:

發送流(示例)

發送端是這樣的:

  1. /**
  2. *
  3. * 發送流
  4. *
  5. */
  6. @Test
  7. public void test5() {
  8. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  9. HttpPost httpPost = new HttpPost("http://localhost:12345/is?name=鄧沙利文");
  10. CloseableHttpResponse response = null;
  11. try {
  12. InputStream is = new ByteArrayInputStream("流啊流~".getBytes());
  13. InputStreamEntity ise = new InputStreamEntity(is);
  14. httpPost.setEntity(ise);
  15. response = httpClient.execute(httpPost);
  16. HttpEntity responseEntity = response.getEntity();
  17. System.out.println("HTTPS響應狀態爲:" + response.getStatusLine());
  18. if (responseEntity != null) {
  19. System.out.println("HTTPS響應內容長度爲:" + responseEntity.getContentLength());
  20. // 主動設置編碼,來防止響應亂碼
  21. String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
  22. System.out.println("HTTPS響應內容爲:" + responseStr);
  23. }
  24. } catch (ParseException | IOException e) {
  25. e.printStackTrace();
  26. } finally {
  27. try {
  28. // 釋放資源
  29. if (httpClient != null) {
  30. httpClient.close();
  31. }
  32. if (response != null) {
  33. response.close();
  34. }
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. }

接收端是這樣的:

 


再次提示:如果想要自己進行測試,可去下面給的項目代碼託管鏈接,將項目clone下來,然後先啓動該
                  SpringBoot項目,然後再運行相關test方法,進行測試。

工具類提示:使用HttpClient時,可以視情況將其寫爲工具類。如:Github上Star非常多的一個HttpClient
                      的工具類是httpclientutil。本人在這裏也推薦使用該工具類,因爲該工具類的編寫者封裝了
                      很多功能在裏面,如果不是有什麼特殊的需求的話,完全可以不用造輪子,可以直接使用
                      該工具類。使用方式很簡單,可詳見https://github.com/Arronlong/httpclientutil


 

^_^ 如有不當之處,歡迎指正

^_^ 代碼託管鏈接
           
   https://github.com/JustryDeng/P.../Abc_HttpClientDemo

^_^ 本文已經被收錄進《程序員成長筆記(五)》,作者JustryDeng

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章