免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
HttpClient詳細使用示例

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

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

HttpClient的主要功能:

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

進入正題


環(huán)境說明:Eclipse、JDK1.8、SpringBoot

準備環(huán)節(jié)

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

第二步:引入fastjson依賴

注:本人引入此依賴的目的是,在后續(xù)示例中,會用到“將對象轉(zhuǎn)化為json字符串的功能”,也可以引其他有此功能的依賴。 

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


詳細使用示例

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

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

GET無參

HttpClient發(fā)送示例:

  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. // 創(chuàng)建Get請求
  11. HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerOne");
  12. // 響應模型
  13. CloseableHttpResponse response = null;
  14. try {
  15. // 由客戶端執(zhí)行(發(fā)送)Get請求
  16. response = httpClient.execute(httpGet);
  17. // 從響應模型中獲取響應實體
  18. HttpEntity responseEntity = response.getEntity();
  19. System.out.println("響應狀態(tài)為:" + response.getStatusLine());
  20. if (responseEntity != null) {
  21. System.out.println("響應內(nèi)容長度為:" + responseEntity.getContentLength());
  22. System.out.println("響應內(nèi)容為:" + 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發(fā)送示例:

  1. /**
  2. * GET---有參測試 (方式一:手動在url后面加上參數(shù))
  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. // 參數(shù)
  11. StringBuffer params = new StringBuffer();
  12. try {
  13. // 字符數(shù)據(jù)最好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. // 創(chuàng)建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. // 由客戶端執(zhí)行(發(fā)送)Get請求
  38. response = httpClient.execute(httpGet);
  39. // 從響應模型中獲取響應實體
  40. HttpEntity responseEntity = response.getEntity();
  41. System.out.println("響應狀態(tài)為:" + response.getStatusLine());
  42. if (responseEntity != null) {
  43. System.out.println("響應內(nèi)容長度為:" + responseEntity.getContentLength());
  44. System.out.println("響應內(nèi)容為:" + 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發(fā)送示例:

  1. /**
  2. * GET---有參測試 (方式二:將參數(shù)放入鍵值對類中,再放入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. // 參數(shù)
  11. URI uri = null;
  12. try {
  13. // 將參數(shù)放入鍵值對類NameValuePair中,再放入集合中
  14. List<NameValuePair> params = new ArrayList<>();
  15. params.add(new BasicNameValuePair("name", "&"));
  16. params.add(new BasicNameValuePair("age", "18"));
  17. // 設置uri信息,并將參數(shù)集合放入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. // 創(chuàng)建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. // 由客戶端執(zhí)行(發(fā)送)Get請求
  43. response = httpClient.execute(httpGet);
  44. // 從響應模型中獲取響應實體
  45. HttpEntity responseEntity = response.getEntity();
  46. System.out.println("響應狀態(tài)為:" + response.getStatusLine());
  47. if (responseEntity != null) {
  48. System.out.println("響應內(nèi)容長度為:" + responseEntity.getContentLength());
  49. System.out.println("響應內(nèi)容為:" + 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發(fā)送示例:

  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. // 創(chuàng)建Post請求
  11. HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerOne");
  12. // 響應模型
  13. CloseableHttpResponse response = null;
  14. try {
  15. // 由客戶端執(zhí)行(發(fā)送)Post請求
  16. response = httpClient.execute(httpPost);
  17. // 從響應模型中獲取響應實體
  18. HttpEntity responseEntity = response.getEntity();
  19. System.out.println("響應狀態(tài)為:" + response.getStatusLine());
  20. if (responseEntity != null) {
  21. System.out.println("響應內(nèi)容長度為:" + responseEntity.getContentLength());
  22. System.out.println("響應內(nèi)容為:" + 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有參(普通參數(shù))

注:POST傳遞普通參數(shù)時,方式與GET一樣即可,這里以直接在url后綴上參數(shù)的方式示例。

HttpClient發(fā)送示例:

  1. /**
  2. * POST---有參測試(普通參數(shù))
  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. // 參數(shù)
  11. StringBuffer params = new StringBuffer();
  12. try {
  13. // 字符數(shù)據(jù)最好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. // 創(chuàng)建Post請求
  21. HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerFour" + "?" + params);
  22. // 設置ContentType(注:如果只是傳普通參數(shù)的話,ContentType不一定非要用application/json)
  23. httpPost.setHeader("Content-Type", "application/json;charset=utf8");
  24. // 響應模型
  25. CloseableHttpResponse response = null;
  26. try {
  27. // 由客戶端執(zhí)行(發(fā)送)Post請求
  28. response = httpClient.execute(httpPost);
  29. // 從響應模型中獲取響應實體
  30. HttpEntity responseEntity = response.getEntity();
  31. System.out.println("響應狀態(tài)為:" + response.getStatusLine());
  32. if (responseEntity != null) {
  33. System.out.println("響應內(nèi)容長度為:" + responseEntity.getContentLength());
  34. System.out.println("響應內(nèi)容為:" + 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有參(對象參數(shù))

先給出User類

HttpClient發(fā)送示例:

  1. /**
  2. * POST---有參測試(對象參數(shù))
  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. // 創(chuàng)建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("姿勢要優(yōu)雅~");
  17. // 我這里利用阿里的fastjson,將Object轉(zhuǎn)換為json字符串;
  18. // (需要導入com.alibaba.fastjson.JSON包)
  19. String jsonString = JSON.toJSONString(user);
  20. StringEntity entity = new StringEntity(jsonString, "UTF-8");
  21. // post請求是將參數(shù)放在請求體里面?zhèn)鬟^去的;這里將entity放入post請求體中
  22. httpPost.setEntity(entity);
  23. httpPost.setHeader("Content-Type", "application/json;charset=utf8");
  24. // 響應模型
  25. CloseableHttpResponse response = null;
  26. try {
  27. // 由客戶端執(zhí)行(發(fā)送)Post請求
  28. response = httpClient.execute(httpPost);
  29. // 從響應模型中獲取響應實體
  30. HttpEntity responseEntity = response.getEntity();
  31. System.out.println("響應狀態(tài)為:" + response.getStatusLine());
  32. if (responseEntity != null) {
  33. System.out.println("響應內(nèi)容長度為:" + responseEntity.getContentLength());
  34. System.out.println("響應內(nèi)容為:" + 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有參(普通參數(shù) + 對象參數(shù))

注:POST傳遞普通參數(shù)時,方式與GET一樣即可,這里以通過URI獲得HttpPost的方式為例。

先給出User類:

HttpClient發(fā)送示例:

  1. /**
  2. * POST---有參測試(普通參數(shù) + 對象參數(shù))
  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. // 創(chuàng)建Post請求
  11. // 參數(shù)
  12. URI uri = null;
  13. try {
  14. // 將參數(shù)放入鍵值對類NameValuePair中,再放入集合中
  15. List<NameValuePair> params = new ArrayList<>();
  16. params.add(new BasicNameValuePair("flag", "4"));
  17. params.add(new BasicNameValuePair("meaning", "這是什么鬼?"));
  18. // 設置uri信息,并將參數(shù)集合放入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. // 創(chuàng)建user參數(shù)
  29. User user = new User();
  30. user.setName("潘曉婷");
  31. user.setAge(18);
  32. user.setGender("女");
  33. user.setMotto("姿勢要優(yōu)雅~");
  34. // 將user對象轉(zhuǎn)換為json字符串,并放入entity中
  35. StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");
  36. // post請求是將參數(shù)放在請求體里面?zhèn)鬟^去的;這里將entity放入post請求體中
  37. httpPost.setEntity(entity);
  38. httpPost.setHeader("Content-Type", "application/json;charset=utf8");
  39. // 響應模型
  40. CloseableHttpResponse response = null;
  41. try {
  42. // 由客戶端執(zhí)行(發(fā)送)Post請求
  43. response = httpClient.execute(httpPost);
  44. // 從響應模型中獲取響應實體
  45. HttpEntity responseEntity = response.getEntity();
  46. System.out.println("響應狀態(tài)為:" + response.getStatusLine());
  47. if (responseEntity != null) {
  48. System.out.println("響應內(nèi)容長度為:" + responseEntity.getContentLength());
  49. System.out.println("響應內(nèi)容為:" + 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. }

對應接收示例:

 

提示:使用HttpClient時,可以視情況將其寫為工具類。

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

^_^ 代碼托管鏈接
           
   https://github.com/JustryDeng/PublicRepository

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

本站僅提供存儲服務,所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
使用HttpClient實現(xiàn)文件的上傳下載
關于調(diào)用接口 Connection reset 問題(使用代理調(diào)接口)
httpClient基礎
HttpClient在HTTP協(xié)議接口測試中的使用
android-working-with-volley-library-1/ , part 6
HttpClient 4.3教程 第一章 基本概念 | 易蹤網(wǎng)
更多類似文章 >>
生活服務
分享 收藏 導長圖 關注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服