Spring+Http請(qǐng)求+HttpClient實(shí)現(xiàn)傳參
一、HttpClient簡(jiǎn)介
HTTP 協(xié)議可能是現(xiàn)在 Internet 上使用得最多、最重要的協(xié)議了,越來越多的 Java 應(yīng)用程序需要直接通過 HTTP 協(xié)議來訪問網(wǎng)絡(luò)資源。雖然在 JDK 的 java net包中已經(jīng)提供了訪問 HTTP 協(xié)議的基本功能,但是對(duì)于大部分應(yīng)用程序來說,JDK 庫(kù)本身提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common 下的子項(xiàng)目,用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。
HTTP和瀏覽器有點(diǎn)像,但卻不是瀏覽器。很多人覺得既然HttpClient是一個(gè)HTTP客戶端編程工具,很多人把他當(dāng)做瀏覽器來理解,但是其實(shí)HttpClient不是瀏覽器,它是一個(gè)HTTP通信庫(kù),因此它只提供一個(gè)通用瀏覽器應(yīng)用程序所期望的功能子集,最根本的區(qū)別是HttpClient中沒有用戶界面,瀏覽器需要一個(gè)渲染引擎來顯示頁(yè)面,并解釋用戶輸入,例如鼠標(biāo)點(diǎn)擊顯示頁(yè)面上的某處,有一個(gè)布局引擎,計(jì)算如何顯示HTML頁(yè)面,包括級(jí)聯(lián)樣式表和圖像。javascript解釋器運(yùn)行嵌入HTML頁(yè)面或從HTML頁(yè)面引用的javascript代碼。來自用戶界面的事件被傳遞到j(luò)avascript解釋器進(jìn)行處理。除此之外,還有用于插件的接口,可以處理Applet,嵌入式媒體對(duì)象(如pdf文件,Quicktime電影和Flash動(dòng)畫)或ActiveX控件(可以執(zhí)行任何操作)。HttpClient只能以編程的方式通過其API用于傳輸和接受HTTP消息。
HttpClient的主要功能:
- 實(shí)現(xiàn)了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
- 支持 HTTPS 協(xié)議
- 支持代理服務(wù)器(Nginx等)等
- 支持自動(dòng)(跳轉(zhuǎn))轉(zhuǎn)向
二、Maven依賴
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.9</version> </dependency>
三、GET無參
/**
* GET---無參測(cè)試
*/
@Test
public void doGetTestOne() {
// 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 創(chuàng)建Get請(qǐng)求
HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerOne");
// 響應(yīng)模型
CloseableHttpResponse response = null;
try {
// 由客戶端執(zhí)行(發(fā)送)Get請(qǐng)求
response = httpClient.execute(httpGet);
// 從響應(yīng)模型中獲取響應(yīng)實(shí)體
HttpEntity responseEntity = response.getEntity();
System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("響應(yīng)內(nèi)容長(zhǎng)度為:" + responseEntity.getContentLength());
System.out.println("響應(yīng)內(nèi)容為:" + 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---有參測(cè)試 (方式一:手動(dòng)在url后面加上參數(shù))
*/
@Test
public void doGetTestWayOne() {
// 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 參數(shù)
StringBuffer params = new StringBuffer();
try {
// 字符數(shù)據(jù)最好encoding以下;這樣一來,某些特殊字符才能傳過去(如:某人的名字就是“&”,不encoding的話,傳不過去)
params.append("name=" + URLEncoder.encode("&", "utf-8"));
params.append("&");
params.append("age=24");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 創(chuàng)建Get請(qǐng)求
HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerTwo" + "?" + params);
// 響應(yīng)模型
CloseableHttpResponse response = null;
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 設(shè)置連接超時(shí)時(shí)間(單位毫秒)
.setConnectTimeout(5000)
// 設(shè)置請(qǐng)求超時(shí)時(shí)間(單位毫秒)
.setConnectionRequestTimeout(5000)
// socket讀寫超時(shí)時(shí)間(單位毫秒)
.setSocketTimeout(5000)
// 設(shè)置是否允許重定向(默認(rèn)為true)
.setRedirectsEnabled(true).build();
// 將上面的配置信息 運(yùn)用到這個(gè)Get請(qǐng)求里
httpGet.setConfig(requestConfig);
// 由客戶端執(zhí)行(發(fā)送)Get請(qǐng)求
response = httpClient.execute(httpGet);
// 從響應(yīng)模型中獲取響應(yīng)實(shí)體
HttpEntity responseEntity = response.getEntity();
System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("響應(yīng)內(nèi)容長(zhǎng)度為:" + responseEntity.getContentLength());
System.out.println("響應(yīng)內(nèi)容為:" + 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---有參測(cè)試 (方式二:將參數(shù)放入鍵值對(duì)類中,再放入U(xiǎn)RI中,從而通過URI得到HttpGet實(shí)例)
*/
@Test
public void doGetTestWayTwo() {
// 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 參數(shù)
URI uri = null;
try {
// 將參數(shù)放入鍵值對(duì)類NameValuePair中,再放入集合中
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("name", "&"));
params.add(new BasicNameValuePair("age", "18"));
// 設(shè)置uri信息,并將參數(shù)集合放入uri;
// 注:這里也支持一個(gè)鍵值對(duì)一個(gè)鍵值對(duì)地往里面放setParameter(String key, String value)
uri = new URIBuilder().setScheme("http").setHost("localhost")
.setPort(12345).setPath("/doGetControllerTwo")
.setParameters(params).build();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
// 創(chuàng)建Get請(qǐng)求
HttpGet httpGet = new HttpGet(uri);
// 響應(yīng)模型
CloseableHttpResponse response = null;
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 設(shè)置連接超時(shí)時(shí)間(單位毫秒)
.setConnectTimeout(5000)
// 設(shè)置請(qǐng)求超時(shí)時(shí)間(單位毫秒)
.setConnectionRequestTimeout(5000)
// socket讀寫超時(shí)時(shí)間(單位毫秒)
.setSocketTimeout(5000)
// 設(shè)置是否允許重定向(默認(rèn)為true)
.setRedirectsEnabled(true).build();
// 將上面的配置信息 運(yùn)用到這個(gè)Get請(qǐng)求里
httpGet.setConfig(requestConfig);
// 由客戶端執(zhí)行(發(fā)送)Get請(qǐng)求
response = httpClient.execute(httpGet);
// 從響應(yīng)模型中獲取響應(yīng)實(shí)體
HttpEntity responseEntity = response.getEntity();
System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("響應(yīng)內(nèi)容長(zhǎng)度為:" + responseEntity.getContentLength());
System.out.println("響應(yīng)內(nèi)容為:" + 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---無參測(cè)試
*/
@Test
public void doPostTestOne() {
// 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 創(chuàng)建Post請(qǐng)求
HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerOne");
// 響應(yīng)模型
CloseableHttpResponse response = null;
try {
// 由客戶端執(zhí)行(發(fā)送)Post請(qǐng)求
response = httpClient.execute(httpPost);
// 從響應(yīng)模型中獲取響應(yīng)實(shí)體
HttpEntity responseEntity = response.getEntity();
System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("響應(yīng)內(nèi)容長(zhǎng)度為:" + responseEntity.getContentLength());
System.out.println("響應(yīng)內(nèi)容為:" + 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有參(普通參數(shù))
注:POST傳遞普通參數(shù)時(shí),方式與GET一樣即可,這里以直接在url后綴上參數(shù)的方式示例。
/**
* POST---有參測(cè)試(普通參數(shù))
*/
@Test
public void doPostTestFour() {
// 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 參數(shù)
StringBuffer params = new StringBuffer();
try {
// 字符數(shù)據(jù)最好encoding以下;這樣一來,某些特殊字符才能傳過去(如:某人的名字就是“&”,不encoding的話,傳不過去)
params.append("name=" + URLEncoder.encode("&", "utf-8"));
params.append("&");
params.append("age=24");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 創(chuàng)建Post請(qǐng)求
HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerFour" + "?" + params);
// 設(shè)置ContentType(注:如果只是傳普通參數(shù)的話,ContentType不一定非要用application/json)
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
// 響應(yīng)模型
CloseableHttpResponse response = null;
try {
// 由客戶端執(zhí)行(發(fā)送)Post請(qǐng)求
response = httpClient.execute(httpPost);
// 從響應(yīng)模型中獲取響應(yīng)實(shí)體
HttpEntity responseEntity = response.getEntity();
System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("響應(yīng)內(nèi)容長(zhǎng)度為:" + responseEntity.getContentLength());
System.out.println("響應(yīng)內(nèi)容為:" + 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有參(對(duì)象參數(shù))
/**
* POST---有參測(cè)試(對(duì)象參數(shù))
*/
@Test
public void doPostTestTwo() {
// 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 創(chuàng)建Post請(qǐng)求
HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerTwo");
User user = new User();
user.setName("潘曉婷");
user.setAge(18);
user.setGender("女");
user.setMotto("姿勢(shì)要優(yōu)雅~");
// 我這里利用阿里的fastjson,將Object轉(zhuǎn)換為json字符串;
// (需要導(dǎo)入com.alibaba.fastjson.JSON包)
String jsonString = JSON.toJSONString(user);
StringEntity entity = new StringEntity(jsonString, "UTF-8");
// post請(qǐng)求是將參數(shù)放在請(qǐng)求體里面?zhèn)鬟^去的;這里將entity放入post請(qǐng)求體中
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
// 響應(yīng)模型
CloseableHttpResponse response = null;
try {
// 由客戶端執(zhí)行(發(fā)送)Post請(qǐng)求
response = httpClient.execute(httpPost);
// 從響應(yīng)模型中獲取響應(yīng)實(shí)體
HttpEntity responseEntity = response.getEntity();
System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("響應(yīng)內(nèi)容長(zhǎng)度為:" + responseEntity.getContentLength());
System.out.println("響應(yīng)內(nèi)容為:" + 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有參(普通參數(shù) + 對(duì)象參數(shù))
注:POST傳遞普通參數(shù)時(shí),方式與GET一樣即可,這里以通過URI獲得HttpPost的方式為例。
/**
* POST---有參測(cè)試(普通參數(shù) + 對(duì)象參數(shù))
*/
@Test
public void doPostTestThree() {
// 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 創(chuàng)建Post請(qǐng)求
// 參數(shù)
URI uri = null;
try {
// 將參數(shù)放入鍵值對(duì)類NameValuePair中,再放入集合中
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("flag", "4"));
params.add(new BasicNameValuePair("meaning", "這是什么鬼?"));
// 設(shè)置uri信息,并將參數(shù)集合放入uri;
// 注:這里也支持一個(gè)鍵值對(duì)一個(gè)鍵值對(duì)地往里面放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");
// 創(chuàng)建user參數(shù)
User user = new User();
user.setName("潘曉婷");
user.setAge(18);
user.setGender("女");
user.setMotto("姿勢(shì)要優(yōu)雅~");
// 將user對(duì)象轉(zhuǎn)換為json字符串,并放入entity中
StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");
// post請(qǐng)求是將參數(shù)放在請(qǐng)求體里面?zhèn)鬟^去的;這里將entity放入post請(qǐng)求體中
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
// 響應(yīng)模型
CloseableHttpResponse response = null;
try {
// 由客戶端執(zhí)行(發(fā)送)Post請(qǐng)求
response = httpClient.execute(httpPost);
// 從響應(yīng)模型中獲取響應(yīng)實(shí)體
HttpEntity responseEntity = response.getEntity();
System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("響應(yīng)內(nèi)容長(zhǎng)度為:" + responseEntity.getContentLength());
System.out.println("響應(yīng)內(nèi)容為:" + 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();
}
}
}
到此這篇關(guān)于Spring+Http請(qǐng)求+HttpClient實(shí)現(xiàn)傳參的文章就介紹到這了,更多相關(guān)Spring+Http請(qǐng)求+HttpClient內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Servlet實(shí)現(xiàn)技術(shù)問答網(wǎng)站系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了基于Servlet實(shí)現(xiàn)技術(shù)問答網(wǎng)站系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04
servlet異步請(qǐng)求的實(shí)現(xiàn)
本文主要介紹了servlet異步請(qǐng)求的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
Java中Date,Calendar,Timestamp的區(qū)別以及相互轉(zhuǎn)換與使用
以下是對(duì)Java中Date,Calendar,Timestamp的區(qū)別以及相互轉(zhuǎn)換與使用進(jìn)行了詳細(xì)的介紹,需要的朋友可以過來參考下2013-09-09
基于SpringMVC接受JSON參數(shù)詳解及常見錯(cuò)誤總結(jié)
下面小編就為大家分享一篇基于SpringMVC接受JSON參數(shù)詳解及常見錯(cuò)誤總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03
詳解spring mvc4使用及json 日期轉(zhuǎn)換解決方案
本篇文章主要介紹了spring mvc4使用及json 日期轉(zhuǎn)換解決方案,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01
Java線程池隊(duì)列PriorityBlockingQueue和SynchronousQueue詳解
這篇文章主要為大家介紹了Java線程池隊(duì)列PriorityBlockingQueue和SynchronousQueue詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12

