Java使用HttpClient詳細(xì)示例
HTTP 協(xié)議可能是現(xiàn)在 Internet 上使用得最多、最重要的協(xié)議了,越來(lái)越多的 Java 應(yīng)用程序需要直接通過(guò) HTTP 協(xié)議來(lái)訪問(wèn)網(wǎng)絡(luò)資源。雖然在 JDK 的 java net包中已經(jīng)提供了訪問(wèn) HTTP 協(xié)議的基本功能,但是對(duì)于大部分應(yīng)用程序來(lái)說(shuō),JDK 庫(kù)本身提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common 下的子項(xiàng)目,用來(lái)提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。
HTTP和瀏覽器有點(diǎn)像,但卻不是瀏覽器。很多人覺(jué)得既然HttpClient是一個(gè)HTTP客戶端編程工具,很多人把他當(dāng)做瀏覽器來(lái)理解,但是其實(shí)HttpClient不是瀏覽器,它是一個(gè)HTTP通信庫(kù),因此它只提供一個(gè)通用瀏覽器應(yīng)用程序所期望的功能子集,最根本的區(qū)別是HttpClient中沒(méi)有用戶界面,瀏覽器需要一個(gè)渲染引擎來(lái)顯示頁(yè)面,并解釋用戶輸入,例如鼠標(biāo)點(diǎn)擊顯示頁(yè)面上的某處,有一個(gè)布局引擎,計(jì)算如何顯示HTML頁(yè)面,包括級(jí)聯(lián)樣式表和圖像。javascript解釋器運(yùn)行嵌入HTML頁(yè)面或從HTML頁(yè)面引用的javascript代碼。來(lái)自用戶界面的事件被傳遞到j(luò)avascript解釋器進(jìn)行處理。除此之外,還有用于插件的接口,可以處理Applet,嵌入式媒體對(duì)象(如pdf文件,Quicktime電影和Flash動(dòng)畫)或ActiveX控件(可以執(zhí)行任何操作)。HttpClient只能以編程的方式通過(guò)其API用于傳輸和接受HTTP消息。
HttpClient的主要功能:
- 實(shí)現(xiàn)了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
- 支持 HTTPS 協(xié)議
- 支持代理服務(wù)器(Nginx等)等
- 支持自動(dòng)(跳轉(zhuǎn))轉(zhuǎn)向
- ……
進(jìn)入正題
環(huán)境說(shuō)明:JDK1.8、SpringBoot
準(zhǔn)備環(huán)節(jié)
第一步:在pom.xml中引入HttpClient的依賴

第二步:引入fastjson依賴

- 注:本人引入此依賴的目的是,在后續(xù)示例中,會(huì)用到“將對(duì)象轉(zhuǎn)化為json字符串的功能”,也可以引其他有此功能的依賴。?
- 注:SpringBoot的基本依賴配置,這里就不再多說(shuō)了。
詳細(xì)使用示例
聲明:此示例中,以JAVA發(fā)送HttpClient(在test里面單元測(cè)試發(fā)送的);也是以JAVA接收的(在controller里面接收的)。
聲明:下面的代碼,本人親測(cè)有效。
GET無(wú)參:
HttpClient發(fā)送示例:
/**
* GET---無(wú)參測(cè)試
*
* @date 2018年7月13日 下午4:18:50
*/
@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();
}
}
}
對(duì)應(yīng)接收示例:

GET有參(方式一:直接拼接URL):
HttpClient發(fā)送示例:
/**
* GET---有參測(cè)試 (方式一:手動(dòng)在url后面加上參數(shù))
*
* @date 2018年7月13日 下午4:19:23
*/
@Test
public void doGetTestWayOne() {
// 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 參數(shù)
StringBuffer params = new StringBuffer();
try {
// 字符數(shù)據(jù)最好encoding以下;這樣一來(lái),某些特殊字符才能傳過(guò)去(如:某人的名字就是“&”,不encoding的話,傳不過(guò)去)
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();
}
}
}
對(duì)應(yīng)接收示例:

GET有參(方式二:使用URI獲得HttpGet):
HttpClient發(fā)送示例:
/**
* GET---有參測(cè)試 (方式二:將參數(shù)放入鍵值對(duì)類中,再放入U(xiǎn)RI中,從而通過(guò)URI得到HttpGet實(shí)例)
*
* @date 2018年7月13日 下午4:19:23
*/
@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();
}
}
}
對(duì)應(yīng)接收示例:

POST無(wú)參:
HttpClient發(fā)送示例:
/**
* POST---無(wú)參測(cè)試
*
* @date 2018年7月13日 下午4:18:50
*/
@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();
}
}
}
對(duì)應(yīng)接收示例:

POST有參(普通參數(shù)):
注:POST傳遞普通參數(shù)時(shí),方式與GET一樣即可,這里以直接在url后綴上參數(shù)的方式示例。
HttpClient發(fā)送示例:
/**
* POST---有參測(cè)試(普通參數(shù))
*
* @date 2018年7月13日 下午4:18:50
*/
@Test
public void doPostTestFour() {
// 獲得Http客戶端(可以理解為:你得先有一個(gè)瀏覽器;注意:實(shí)際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 參數(shù)
StringBuffer params = new StringBuffer();
try {
// 字符數(shù)據(jù)最好encoding以下;這樣一來(lái),某些特殊字符才能傳過(guò)去(如:某人的名字就是“&”,不encoding的話,傳不過(guò)去)
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();
}
}
}
對(duì)應(yīng)接收示例:

POST有參(對(duì)象參數(shù)):
先給出User類

HttpClient發(fā)送示例:
/**
* POST---有參測(cè)試(對(duì)象參數(shù))
*
* @date 2018年7月13日 下午4:18:50
*/
@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)鬟^(guò)去的;這里將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();
}
}
}
對(duì)應(yīng)接收示例:

POST有參(普通參數(shù) + 對(duì)象參數(shù)):
注:POST傳遞普通參數(shù)時(shí),方式與GET一樣即可,這里以通過(guò)URI獲得HttpPost的方式為例。
先給出User類:

HttpClient發(fā)送示例:
/**
* POST---有參測(cè)試(普通參數(shù) + 對(duì)象參數(shù))
*
* @date 2018年7月13日 下午4:18:50
*/
@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)鬟^(guò)去的;這里將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();
}
}
}
對(duì)應(yīng)接收示例:

對(duì)評(píng)論區(qū)關(guān)注度較高的問(wèn)題進(jìn)行相關(guān)補(bǔ)充:
提示:如果想要知道完整的具體的代碼及測(cè)試細(xì)節(jié),可去下面給的項(xiàng)目代碼托管鏈接,將項(xiàng)目clone下來(lái)進(jìn)行觀察。如果需要運(yùn)行測(cè)試,可以先啟動(dòng)該SpringBoot項(xiàng)目,然后再運(yùn)行相關(guān)test方法,進(jìn)行測(cè)試。
解決響應(yīng)亂碼問(wèn)題(示例):

進(jìn)行HTTPS請(qǐng)求并進(jìn)行(或不進(jìn)行)證書校驗(yàn)(示例):
使用示例:

相關(guān)方法詳情(非完美封裝):
/**
* 根據(jù)是否是https請(qǐng)求,獲取HttpClient客戶端
*
* TODO 本人這里沒(méi)有進(jìn)行完美封裝。對(duì)于 校不校驗(yàn)校驗(yàn)證書的選擇,本人這里是寫死
* 在代碼里面的,你們?cè)谑褂脮r(shí),可以靈活二次封裝。
*
* 提示: 此工具類的封裝、相關(guān)客戶端、服務(wù)端證書的生成,可參考我的這篇博客:
* <linked>https://blog.csdn.net/justry_deng/article/details/91569132</linked>
*
*
* @param isHttps 是否是HTTPS請(qǐng)求
*
* @return HttpClient實(shí)例
* @date 2019/9/18 17:57
*/
private CloseableHttpClient getHttpClient(boolean isHttps) {
CloseableHttpClient httpClient;
if (isHttps) {
SSLConnectionSocketFactory sslSocketFactory;
try {
/// 如果不作證書校驗(yàn)的話
sslSocketFactory = getSocketFactory(false, null, null);
/// 如果需要證書檢驗(yàn)的話
// 證書
//InputStream ca = this.getClass().getClassLoader().getResourceAsStream("client/ds.crt");
// 證書的別名,即:key。 注:cAalias只需要保證唯一即可,不過(guò)推薦使用生成keystore時(shí)使用的別名。
// String cAalias = System.currentTimeMillis() + "" + new SecureRandom().nextInt(1000);
//sslSocketFactory = getSocketFactory(true, ca, cAalias);
} catch (Exception e) {
throw new RuntimeException(e);
}
httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
return httpClient;
}
httpClient = HttpClientBuilder.create().build();
return httpClient;
}
/**
* HTTPS輔助方法, 為HTTPS請(qǐng)求 創(chuàng)建SSLSocketFactory實(shí)例、TrustManager實(shí)例
*
* @param needVerifyCa
* 是否需要檢驗(yàn)CA證書(即:是否需要檢驗(yàn)服務(wù)器的身份)
* @param caInputStream
* CA證書。(若不需要檢驗(yàn)證書,那么此處傳null即可)
* @param cAalias
* 別名。(若不需要檢驗(yàn)證書,那么此處傳null即可)
* 注意:別名應(yīng)該是唯一的, 別名不要和其他的別名一樣,否者會(huì)覆蓋之前的相同別名的證書信息。別名即key-value中的key。
*
* @return SSLConnectionSocketFactory實(shí)例
* @throws NoSuchAlgorithmException
* 異常信息
* @throws CertificateException
* 異常信息
* @throws KeyStoreException
* 異常信息
* @throws IOException
* 異常信息
* @throws KeyManagementException
* 異常信息
* @date 2019/6/11 19:52
*/
private static SSLConnectionSocketFactory getSocketFactory(boolean needVerifyCa, InputStream caInputStream, String cAalias)
throws CertificateException, NoSuchAlgorithmException, KeyStoreException,
IOException, KeyManagementException {
X509TrustManager x509TrustManager;
// https請(qǐng)求,需要校驗(yàn)證書
if (needVerifyCa) {
KeyStore keyStore = getKeyStore(caInputStream, cAalias);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
x509TrustManager = (X509TrustManager) trustManagers[0];
// 這里傳TLS或SSL其實(shí)都可以的
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom());
return new SSLConnectionSocketFactory(sslContext);
}
// https請(qǐng)求,不作證書校驗(yàn)
x509TrustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
// 不驗(yàn)證
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom());
return new SSLConnectionSocketFactory(sslContext);
}
/**
* 獲取(密鑰及證書)倉(cāng)庫(kù)
* 注:該倉(cāng)庫(kù)用于存放 密鑰以及證書
*
* @param caInputStream
* CA證書(此證書應(yīng)由要訪問(wèn)的服務(wù)端提供)
* @param cAalias
* 別名
* 注意:別名應(yīng)該是唯一的, 別名不要和其他的別名一樣,否者會(huì)覆蓋之前的相同別名的證書信息。別名即key-value中的key。
* @return 密鑰、證書 倉(cāng)庫(kù)
* @throws KeyStoreException 異常信息
* @throws CertificateException 異常信息
* @throws IOException 異常信息
* @throws NoSuchAlgorithmException 異常信息
* @date 2019/6/11 18:48
*/
private static KeyStore getKeyStore(InputStream caInputStream, String cAalias)
throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
// 證書工廠
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
// 秘鑰倉(cāng)庫(kù)
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
keyStore.setCertificateEntry(cAalias, certificateFactory.generateCertificate(caInputStream));
return keyStore;
}
application/x-www-form-urlencoded表單請(qǐng)求(示例):

發(fā)送文件(示例):
準(zhǔn)備工作:
如果想要靈活方便的傳輸文件的話,除了引入org.apache.httpcomponents基本的httpclient依賴外再額外引入org.apache.httpcomponents的httpmime依賴。
P.S.:即便不引入httpmime依賴,也是能傳輸文件的,不過(guò)功能不夠強(qiáng)大。
在pom.xml中額外引入:
<!--
如果需要靈活的傳輸文件,引入此依賴后會(huì)更加方便
-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.5</version>
</dependency>
發(fā)送端是這樣的:
/**
*
* 發(fā)送文件
*
* multipart/form-data傳遞文件(及相關(guān)信息)
*
* 注:如果想要靈活方便的傳輸文件的話,
* 除了引入org.apache.httpcomponents基本的httpclient依賴外
* 再額外引入org.apache.httpcomponents的httpmime依賴。
* 追注:即便不引入httpmime依賴,也是能傳輸文件的,不過(guò)功能不夠強(qiáng)大。
*
*/
@Test
public void test4() {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://localhost:12345/file");
CloseableHttpResponse response = null;
try {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// 第一個(gè)文件
String filesKey = "files";
File file1 = new File("C:\\Users\\JustryDeng\\Desktop\\back.jpg");
multipartEntityBuilder.addBinaryBody(filesKey, file1);
// 第二個(gè)文件(多個(gè)文件的話,使用同一個(gè)key就行,后端用數(shù)組或集合進(jìn)行接收即可)
File file2 = new File("C:\\Users\\JustryDeng\\Desktop\\頭像.jpg");
// 防止服務(wù)端收到的文件名亂碼。 我們這里可以先將文件名URLEncode,然后服務(wù)端拿到文件名時(shí)在URLDecode。就能避免亂碼問(wèn)題。
// 文件名其實(shí)是放在請(qǐng)求頭的Content-Disposition里面進(jìn)行傳輸?shù)?,如其值為form-data; name="files"; filename="頭像.jpg"
multipartEntityBuilder.addBinaryBody(filesKey, file2, ContentType.DEFAULT_BINARY, URLEncoder.encode(file2.getName(), "utf-8"));
// 其它參數(shù)(注:自定義contentType,設(shè)置UTF-8是為了防止服務(wù)端拿到的參數(shù)出現(xiàn)亂碼)
ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
multipartEntityBuilder.addTextBody("name", "鄧沙利文", contentType);
multipartEntityBuilder.addTextBody("age", "25", contentType);
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
System.out.println("HTTPS響應(yīng)狀態(tài)為:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("HTTPS響應(yīng)內(nèi)容長(zhǎng)度為:" + responseEntity.getContentLength());
// 主動(dòng)設(shè)置編碼,來(lái)防止響應(yīng)亂碼
String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
System.out.println("HTTPS響應(yīng)內(nèi)容為:" + responseStr);
}
} catch (ParseException | IOException e) {
e.printStackTrace();
} finally {
try {
// 釋放資源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
接收端是這樣的:

發(fā)送流(示例):
發(fā)送端是這樣的:
/**
*
* 發(fā)送流
*
*/
@Test
public void test5() {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://localhost:12345/is?name=鄧沙利文");
CloseableHttpResponse response = null;
try {
InputStream is = new ByteArrayInputStream("流啊流~".getBytes());
InputStreamEntity ise = new InputStreamEntity(is);
httpPost.setEntity(ise);
response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
System.out.println("HTTPS響應(yīng)狀態(tài)為:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("HTTPS響應(yīng)內(nèi)容長(zhǎng)度為:" + responseEntity.getContentLength());
// 主動(dòng)設(shè)置編碼,來(lái)防止響應(yīng)亂碼
String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
System.out.println("HTTPS響應(yīng)內(nèi)容為:" + responseStr);
}
} catch (ParseException | IOException e) {
e.printStackTrace();
} finally {
try {
// 釋放資源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
接收端是這樣的:

再次提示:如果想要自己進(jìn)行測(cè)試,可去下面給的項(xiàng)目代碼托管鏈接,將項(xiàng)目clone下來(lái),然后先啟動(dòng)該SpringBoot項(xiàng)目,然后再運(yùn)行相關(guān)test方法,進(jìn)行測(cè)試。
工具類提示:使用HttpClient時(shí),可以視情況將其寫為工具類。如:Github上Star非常多的一個(gè)HttpClient的工具類是httpclientutil。本人在這里也推薦使用該工具類,因?yàn)樵摴ぞ哳惖木帉懻叻庋b了很多功能在里面,如果不是有什么特殊的需求的話,完全可以不用造輪子,可以直接使用該工具類。使用方式很簡(jiǎn)單,可詳見(jiàn)https://github.com/Arronlong/httpclientutil。
以上所述是小編給大家介紹的Java使用HttpClient詳細(xì)示例,希望對(duì)大家有所幫助。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
springboot啟動(dòng)feign項(xiàng)目報(bào)錯(cuò):Service id not legal hostnam的解決
這篇文章主要介紹了springboot啟動(dòng)feign項(xiàng)目報(bào)錯(cuò):Service id not legal hostnam的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
Jenkins初級(jí)應(yīng)用之Invoke?Phing?targets插件配置
這篇文章主要為大家介紹了Jenkins初級(jí)應(yīng)用之Invoke?Phing?targets的插件配置,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪<BR>2022-04-04
Java調(diào)用DOS實(shí)現(xiàn)定時(shí)關(guān)機(jī)的實(shí)例
Java調(diào)用DOS實(shí)現(xiàn)定時(shí)關(guān)機(jī)的實(shí)例,需要的朋友可以參考一下2013-04-04
Mapstruct對(duì)象插入數(shù)據(jù)庫(kù)某個(gè)字段總是為空的bug詳解
這篇文章主要為大家介紹了在一次需求開發(fā)Mapstruct中對(duì)象插入數(shù)據(jù)庫(kù)某個(gè)字段總是為空的bug問(wèn)題詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
JAVA根據(jù)ip地址獲取歸屬地的實(shí)現(xiàn)方法
本文主要介紹了JAVA根據(jù)ip地址獲取歸屬地的實(shí)現(xiàn)方法,要通過(guò)Java程序獲取IP地址對(duì)應(yīng)的城市,需要借助第三方的IP地址庫(kù),下面就來(lái)介紹一下,感興趣的可以了解一下2023-10-10
Swagger2配置方式(解決404報(bào)錯(cuò))
這篇文章主要介紹了Swagger2配置方式(解決404報(bào)錯(cuò)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
java小知識(shí)之查詢數(shù)據(jù)庫(kù)數(shù)據(jù)的元信息
這篇文章主要給大家介紹了關(guān)于java小知識(shí)之查詢數(shù)據(jù)庫(kù)數(shù)據(jù)的元信息,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2021-10-10

