国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術文章
文章詳情頁

Spring+Http請求+HttpClient實現傳參

瀏覽:4日期:2023-09-15 09:28:31

一、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等)等 支持自動(跳轉)轉向

二、Maven依賴

<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.9</version></dependency>

三、GET無參

/** * GET---無參測試 */ @Test public void doGetTestOne() { // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 創建Get請求 HttpGet httpGet = new HttpGet('http://localhost:12345/doGetControllerOne'); // 響應模型 CloseableHttpResponse response = null; try { // 由客戶端執行(發送)Get請求 response = httpClient.execute(httpGet); // 從響應模型中獲取響應實體 HttpEntity responseEntity = response.getEntity(); System.out.println('響應狀態為:' + response.getStatusLine()); if (responseEntity != null) {System.out.println('響應內容長度為:' + responseEntity.getContentLength());System.out.println('響應內容為:' + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try {// 釋放資源if (httpClient != null) { httpClient.close();}if (response != null) { response.close();} } catch (IOException e) {e.printStackTrace(); } } }

四、GET有參

拼接

/** * GET---有參測試 (方式一:手動在url后面加上參數) */ @Test public void doGetTestWayOne() { // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 參數 StringBuffer params = new StringBuffer(); try { // 字符數據最好encoding以下;這樣一來,某些特殊字符才能傳過去(如:某人的名字就是“&”,不encoding的話,傳不過去) params.append('name=' + URLEncoder.encode('&', 'utf-8')); params.append('&'); params.append('age=24'); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // 創建Get請求 HttpGet httpGet = new HttpGet('http://localhost:12345/doGetControllerTwo' + '?' + params); // 響應模型 CloseableHttpResponse response = null; try { // 配置信息 RequestConfig requestConfig = RequestConfig.custom() // 設置連接超時時間(單位毫秒) .setConnectTimeout(5000) // 設置請求超時時間(單位毫秒) .setConnectionRequestTimeout(5000) // socket讀寫超時時間(單位毫秒) .setSocketTimeout(5000) // 設置是否允許重定向(默認為true) .setRedirectsEnabled(true).build(); // 將上面的配置信息 運用到這個Get請求里 httpGet.setConfig(requestConfig); // 由客戶端執行(發送)Get請求 response = httpClient.execute(httpGet); // 從響應模型中獲取響應實體 HttpEntity responseEntity = response.getEntity(); System.out.println('響應狀態為:' + response.getStatusLine()); if (responseEntity != null) {System.out.println('響應內容長度為:' + responseEntity.getContentLength());System.out.println('響應內容為:' + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try {// 釋放資源if (httpClient != null) { httpClient.close();}if (response != null) { response.close();} } catch (IOException e) {e.printStackTrace(); } } }

URI獲得HttpGet

/** * GET---有參測試 (方式二:將參數放入鍵值對類中,再放入URI中,從而通過URI得到HttpGet實例) */ @Test public void doGetTestWayTwo() { // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 參數 URI uri = null; try { // 將參數放入鍵值對類NameValuePair中,再放入集合中 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair('name', '&')); params.add(new BasicNameValuePair('age', '18')); // 設置uri信息,并將參數集合放入uri; // 注:這里也支持一個鍵值對一個鍵值對地往里面放setParameter(String key, String value) uri = new URIBuilder().setScheme('http').setHost('localhost') .setPort(12345).setPath('/doGetControllerTwo') .setParameters(params).build(); } catch (URISyntaxException e1) { e1.printStackTrace(); } // 創建Get請求 HttpGet httpGet = new HttpGet(uri); // 響應模型 CloseableHttpResponse response = null; try { // 配置信息 RequestConfig requestConfig = RequestConfig.custom() // 設置連接超時時間(單位毫秒) .setConnectTimeout(5000) // 設置請求超時時間(單位毫秒) .setConnectionRequestTimeout(5000) // socket讀寫超時時間(單位毫秒) .setSocketTimeout(5000) // 設置是否允許重定向(默認為true) .setRedirectsEnabled(true).build(); // 將上面的配置信息 運用到這個Get請求里 httpGet.setConfig(requestConfig); // 由客戶端執行(發送)Get請求 response = httpClient.execute(httpGet); // 從響應模型中獲取響應實體 HttpEntity responseEntity = response.getEntity(); System.out.println('響應狀態為:' + response.getStatusLine()); if (responseEntity != null) {System.out.println('響應內容長度為:' + responseEntity.getContentLength());System.out.println('響應內容為:' + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try {// 釋放資源if (httpClient != null) { httpClient.close();}if (response != null) { response.close();} } catch (IOException e) {e.printStackTrace(); } } }

五、POST無參

/** * POST---無參測試 */ @Test public void doPostTestOne() { // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 創建Post請求 HttpPost httpPost = new HttpPost('http://localhost:12345/doPostControllerOne'); // 響應模型 CloseableHttpResponse response = null; try { // 由客戶端執行(發送)Post請求 response = httpClient.execute(httpPost); // 從響應模型中獲取響應實體 HttpEntity responseEntity = response.getEntity(); System.out.println('響應狀態為:' + response.getStatusLine()); if (responseEntity != null) {System.out.println('響應內容長度為:' + responseEntity.getContentLength());System.out.println('響應內容為:' + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try {// 釋放資源if (httpClient != null) { httpClient.close();}if (response != null) { response.close();} } catch (IOException e) {e.printStackTrace(); } } }

六、POST有參(普通參數)

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

/** * POST---有參測試(普通參數) */ @Test public void doPostTestFour() { // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 參數 StringBuffer params = new StringBuffer(); try { // 字符數據最好encoding以下;這樣一來,某些特殊字符才能傳過去(如:某人的名字就是“&”,不encoding的話,傳不過去) params.append('name=' + URLEncoder.encode('&', 'utf-8')); params.append('&'); params.append('age=24'); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // 創建Post請求 HttpPost httpPost = new HttpPost('http://localhost:12345/doPostControllerFour' + '?' + params); // 設置ContentType(注:如果只是傳普通參數的話,ContentType不一定非要用application/json) httpPost.setHeader('Content-Type', 'application/json;charset=utf8'); // 響應模型 CloseableHttpResponse response = null; try { // 由客戶端執行(發送)Post請求 response = httpClient.execute(httpPost); // 從響應模型中獲取響應實體 HttpEntity responseEntity = response.getEntity(); System.out.println('響應狀態為:' + response.getStatusLine()); if (responseEntity != null) {System.out.println('響應內容長度為:' + responseEntity.getContentLength());System.out.println('響應內容為:' + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try {// 釋放資源if (httpClient != null) { httpClient.close();}if (response != null) { response.close();} } catch (IOException e) {e.printStackTrace(); } } }

七、POST有參(對象參數)

/** * POST---有參測試(對象參數) */ @Test public void doPostTestTwo() { // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 創建Post請求 HttpPost httpPost = new HttpPost('http://localhost:12345/doPostControllerTwo'); User user = new User(); user.setName('潘曉婷'); user.setAge(18); user.setGender('女'); user.setMotto('姿勢要優雅~'); // 我這里利用阿里的fastjson,將Object轉換為json字符串; // (需要導入com.alibaba.fastjson.JSON包) String jsonString = JSON.toJSONString(user); StringEntity entity = new StringEntity(jsonString, 'UTF-8'); // post請求是將參數放在請求體里面傳過去的;這里將entity放入post請求體中 httpPost.setEntity(entity); httpPost.setHeader('Content-Type', 'application/json;charset=utf8'); // 響應模型 CloseableHttpResponse response = null; try { // 由客戶端執行(發送)Post請求 response = httpClient.execute(httpPost); // 從響應模型中獲取響應實體 HttpEntity responseEntity = response.getEntity(); System.out.println('響應狀態為:' + response.getStatusLine()); if (responseEntity != null) {System.out.println('響應內容長度為:' + responseEntity.getContentLength());System.out.println('響應內容為:' + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try {// 釋放資源if (httpClient != null) { httpClient.close();}if (response != null) { response.close();} } catch (IOException e) {e.printStackTrace(); } } }

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

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

/** * POST---有參測試(普通參數 + 對象參數) */ @Test public void doPostTestThree() { // 獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 創建Post請求 // 參數 URI uri = null; try { // 將參數放入鍵值對類NameValuePair中,再放入集合中 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair('flag', '4')); params.add(new BasicNameValuePair('meaning', '這是什么鬼?')); // 設置uri信息,并將參數集合放入uri; // 注:這里也支持一個鍵值對一個鍵值對地往里面放setParameter(String key, String value) uri = new URIBuilder().setScheme('http').setHost('localhost').setPort(12345) .setPath('/doPostControllerThree').setParameters(params).build(); } catch (URISyntaxException e1) { e1.printStackTrace(); } HttpPost httpPost = new HttpPost(uri); // HttpPost httpPost = new // HttpPost('http://localhost:12345/doPostControllerThree1'); // 創建user參數 User user = new User(); user.setName('潘曉婷'); user.setAge(18); user.setGender('女'); user.setMotto('姿勢要優雅~'); // 將user對象轉換為json字符串,并放入entity中 StringEntity entity = new StringEntity(JSON.toJSONString(user), 'UTF-8'); // post請求是將參數放在請求體里面傳過去的;這里將entity放入post請求體中 httpPost.setEntity(entity); httpPost.setHeader('Content-Type', 'application/json;charset=utf8'); // 響應模型 CloseableHttpResponse response = null; try { // 由客戶端執行(發送)Post請求 response = httpClient.execute(httpPost); // 從響應模型中獲取響應實體 HttpEntity responseEntity = response.getEntity(); System.out.println('響應狀態為:' + response.getStatusLine()); if (responseEntity != null) {System.out.println('響應內容長度為:' + responseEntity.getContentLength());System.out.println('響應內容為:' + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try {// 釋放資源if (httpClient != null) { httpClient.close();}if (response != null) { response.close();} } catch (IOException e) {e.printStackTrace(); } } }

到此這篇關于Spring+Http請求+HttpClient實現傳參的文章就介紹到這了,更多相關Spring+Http請求+HttpClient內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 国产亚洲精品激情一区二区三区 | 亚洲国产第一区二区香蕉 | 大伊香蕉精品视频在线观看 | 欧美同性videos在线可播放 | 99re在线精品视频 | 久揄揄鲁一二三四区高清在线 | 国产在线综合一区二区三区 | 日韩午夜在线视频不卡片 | 国产三级日本三级美三级 | 久久国产情侣 | 日本亚洲综合 | 免费看一级欧美毛片 | 久久久免费观看视频 | 国产三级借妻 | 亚洲一区二区天海翼 | 久久网免费| 波多野结衣一区二区在线 | 国产精品国内免费一区二区三区 | 欧美一级特黄特黄毛片 | 亚洲第一网色综合久久 | 最新国产三级在线观看不卡 | 麻豆国产一区 | 亚洲精品99久久一区二区三区 | 亚洲最大情网站在线观看 | 国产精品视频自拍 | 91av成年影院在线播放 | 亚洲精品成人一区二区 | 在线观看欧美一区 | 欧美一区二区三区久久综合 | 亚洲欧洲一区二区三区在线 | 美日韩一区二区三区 | 国内精品久久久久久影院老狼 | 国产三级视频在线播放 | 韩国精品欧美一区二区三区 | 成人综合婷婷国产精品久久免费 | a级片在线观看 | 亚洲视频在线免费 | 欧美国产成人精品一区二区三区 | 免费人成黄页网站在线观看 | 99视频免费| 日本亚洲免费 |