HttpClient 詳解
參考 https://blog.csdn.net/justry_deng/article/details/81042379
感謝大佬分享的demo
自己練習下,記錄只爲了下次更方便的查找,侵權刪
http 請求,apache 的一套封裝不錯的http請求
下面的案例都是先有http請求的,再有接口。
get 無參請求
/**
* get 無參請求
*/
@Test
public void doGetTestOne() {
// 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 創建Get請求
HttpGet httpGet = new HttpGet("http://192.168.6.9:8060/ronghe/exBox/v1/getNoParams");
// 響應模型
CloseableHttpResponse response = null;
try {
// 由客戶端執行(發送)Get請求
response = httpClient.execute(httpGet);
// 從響應模型中獲取響應實體
org.apache.http.HttpEntity responseEntity = response.getEntity();
System.out.println("響應狀態爲:" + response.getStatusLine());// 響應狀態爲:HTTP/1.1 200
if (responseEntity != null) {
System.out.println("響應內容長度爲:" + responseEntity.getContentLength());// 響應內容長度爲:3
System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));//響應內容爲:123
}
} catch (ClientProtocolException 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();
}
}
}
@GetMapping("/v1/getNoParams")
public String getNoParams(){
return "123";
}
GET有參(方式一:直接拼接URL):
/**
* get 有參請求(通過url方式傳參)
*/
@Test
public void doGetTestWayOne() {
// 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 參數
StringBuffer params = new StringBuffer();
try {
// 字符數據最好encoding以下;這樣一來,某些特殊字符才能傳過去(如:某人的名字就是“&”,不encoding的話,傳不過去)
params.append("username=" + URLEncoder.encode("&", "utf-8"));
// params.append("&");
// params.append("age=24");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 創建Get請求
HttpGet httpGet = new HttpGet("http://192.168.6.9:8060/ronghe/exBox/v1/getParamsByUrl" + "?" + 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);
// 從響應模型中獲取響應實體
org.apache.http.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 (IOException e) {
e.printStackTrace();
} finally {
try {
// 釋放資源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@GetMapping("/v1/getParamsByUrl")
public String getParamsByUrl(String username){
return username;
}
GET—有參測試 (方式二:將參數放入鍵值對類中)
/**
* 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("username", "&"));
// 設置uri信息,並將參數集合放入uri;
// 注:這裏也支持一個鍵值對一個鍵值對地往裏面放setParameter(String key, String value)
uri = new URIBuilder().setScheme("http").setHost("192.168.6.9")
.setPort(8060).setPath("/ronghe/exBox/v1/getParams")
.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);
// 從響應模型中獲取響應實體
org.apache.http.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 (IOException e) {
e.printStackTrace();
} finally {
try {
// 釋放資源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@GetMapping("/v1/getParams")
public String getParams(String username){
log.info("getNoParams: " + username);
return username;
}
post 無參請求
/**
* POST---無參測試
*/
@Test
public void doPostTestOne() {
// 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 創建Post請求
HttpPost httpPost = new HttpPost("http://192.168.6.9:8060/ronghe/exBox/v1/postForNoParams");
// 響應模型
CloseableHttpResponse response = null;
try {
// 由客戶端執行(發送)Post請求
response = httpClient.execute(httpPost);
// 從響應模型中獲取響應實體
org.apache.http.HttpEntity responseEntity = response.getEntity();
System.out.println("響應狀態爲:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));//響應內容爲:123
}
} catch (ClientProtocolException 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();
}
}
}
@PostMapping("/v1/postForNoParams")
public String postForNoParams(){
return "123";
}
POST有參(普通參數)
/**
* POST---有參測試(普通參數)
*/
@Test
public void doPostTestFour() {
// 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 參數
StringBuffer params = new StringBuffer();
try {
// 字符數據最好encoding以下;這樣一來,某些特殊字符才能傳過去(如:某人的名字就是“&”,不encoding的話,傳不過去)
params.append("username=" + URLEncoder.encode("&", "utf-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 創建Post請求
HttpPost httpPost = new HttpPost("http://192.168.6.9:8060/ronghe/exBox/v1/postForParams" + "?" + params);
// 設置ContentType(注:如果只是傳普通參數的話,ContentType不一定非要用application/json)
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
// 響應模型
CloseableHttpResponse response = null;
try {
// 由客戶端執行(發送)Post請求
response = httpClient.execute(httpPost);
// 從響應模型中獲取響應實體
org.apache.http.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 (IOException e) {
e.printStackTrace();
} finally {
try {
// 釋放資源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@PostMapping("/v1/postForParams")
public String postForParams(String username){
log.info("postForParams"+username);
return username;
}
POST有參(對象參數)
@Test
public void doPostTestTwo() {
// 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 創建Post請求
HttpPost httpPost = new HttpPost("http://192.168.6.9:8060/ronghe/exBox/v1/postForObject");
User user = new User("123");
// 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 =
org.apache.http.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 (IOException e) {
e.printStackTrace();
} finally {
try {
// 釋放資源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@PostMapping("/v1/postForObject")
public String postForObject(@RequestBody User user){
log.info("postForParams"+user.getUsername());
return user.getUsername();
}
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("version", "1.0.0"));
// 設置uri信息,並將參數集合放入uri;
// 注:這裏也支持一個鍵值對一個鍵值對地往裏面放setParameter(String key, String value)
// http://192.168.6.9:8060/ronghe/exBox/v1/postForParamsAndObject
uri = new URIBuilder().setScheme("http").setHost("192.168.6.9").setPort(8060)
.setPath("/ronghe/exBox/v1/postForParamsAndObject").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("123");
// 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);
// 從響應模型中獲取響應實體
org.apache.http.HttpEntity responseEntity = response.getEntity();
System.out.println("響應狀態爲:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
//String res = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8); // 獲取遠程數據,主動修改編碼集
System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));//響應內容爲:123-1.0.0
}
} catch (ClientProtocolException 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();
}
}
}
@PostMapping("/v1/postForParamsAndObject")
public String postForParamsAndObject(String version , @RequestBody User user){
log.info("postForParamsAndObject:"+user.getUsername() + " version:"+ version);
return StringUtils.join(new String[]{user.getUsername(),version},"-");
}
解決亂碼
參考上面一個例子,補充處
進行HTTPS請求並進行(或不進行)證書校驗(示例)
暫未測試,請參考
https://blog.csdn.net/justry_deng/article/details/81042379
application/x-www-form-urlencoded表單請求(示例)
/**
* get 無參請求(form 請求)
*/
@Test
public void doForm() {
// 獲得Http客戶端(可以理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 創建Get請求
HttpGet httpGet = new HttpGet("http://localhost:8060/ronghe/exBox/v1/getForm");
httpGet.setHeader("Content-Type","application/x-www-form-urlencoded");
// 響應模型
CloseableHttpResponse response = null;
try {
// 由客戶端執行(發送)Get請求
response = httpClient.execute(httpGet);
// 從響應模型中獲取響應實體
org.apache.http.HttpEntity responseEntity = response.getEntity();
System.out.println("響應狀態爲:" + response.getStatusLine());// 響應狀態爲:HTTP/1.1 200
if (responseEntity != null) {
System.out.println("響應內容長度爲:" + responseEntity.getContentLength());// 響應內容長度爲:3
System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));//響應內容爲:123
}
} catch (ClientProtocolException 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();
}
}
}
/**
* 表單請求
* @return
*/
@GetMapping(value = "/v1/getForm",consumes = "application/x-www-form-urlencoded")
public String getForm(){
return "123";
}