引入相關依賴:(本文會用到這三條)java
org.apache.httpcomponentsspring
httpclientapache
4.5.9json
com.alibabaapp
fastjsonsocket
1.2.47ide
org.springframework.bootspring-boot
spring-boot-configuration-processor工具
truepost
建立HttpClientUtil工具類,代碼以下:
package com.test.demo;
import com.alibaba.fastjson.JSON;
import com.test.demo.model.User;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
/**
* ClassName: HttpClientTest
* Package: com.test.demo
* Description: httpClient方法封裝
* Datetime: 2020/1/13 10:45
* Author: zhoukaishun
*/
@Component
public class HttpClientUtil {
@Autowired
private HttpClientConfigure httpClientConfigure;
/**
* @description GET封裝
* @author zhoukaishun
* @date 2020/1/13 13:12
*/
public void doGetHttp(List params,Boolean haveParams) {
// 得到Http客戶端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 參數
URI uri = null;
try {
// 設置uri信息,並將參數集合放入uri;
if(haveParams){//有參調用
uri = new URIBuilder().setScheme(httpClientConfigure.getScheme()).setHost(httpClientConfigure.getHost())
.setPort(httpClientConfigure.getPort()).setPath(httpClientConfigure.getMapPath().get("interface2"))
.setParameters(params).build();
}else{//無參調用
uri = new URIBuilder().setScheme(httpClientConfigure.getScheme()).setHost(httpClientConfigure.getHost())
.setPort(httpClientConfigure.getPort()).setPath(httpClientConfigure.getMapPath().get("interface1"))
.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();
}
}
}
/**
* @description POST封裝
* @author zhoukaishun
* @date 2020/1/13 14:01
*/
public void doPostHttp(User user,Boolean haveParam) {
// 得到Http客戶端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
URI uri = null;
try {
// 設置uri信息,並將參數集合放入uri;
uri = new URIBuilder().setScheme(httpClientConfigure.getScheme()).setHost(httpClientConfigure.getHost())
.setPort(httpClientConfigure.getPort())
.setPath(haveParam?httpClientConfigure.getMapPath().get("interface4"):httpClientConfigure.getMapPath().get("interface3"))
.build();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
// 建立Post請求
HttpPost httpPost = new HttpPost(uri);
if(haveParam){
//入參
// 利用阿里的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));
}鄭州婦科醫院哪家好 https://yiyuan.120ask.com/zzfck/
} 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();
}
}
}
}
其中大部分代碼基本不變,只有對url的拼接作了一些處理,能夠看到咱們注入了一個HttpClientConfigure實例,由於咱們須要訪問的路徑狀況有不少種,可是咱們不可能每次都去改util下的url拼接代碼,因此引入一個HttpClientConfigure,這是我自定義的一個類,用於存儲咱們拼接url可能遇到的狀況。代碼以下:
package com.test.demo;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* ClassName: HttpClientConfigure
* Package: com.test.demo
* Description: 接收配置信息
* Datetime: 2020/1/13 14:41
* Author: zhoukaishun
*/
@Component
@ConfigurationProperties(prefix="httpclientconfigure")
@Data
public class HttpClientConfigure {
private Map mapPath = new HashMap<>();
private String scheme;
private String host;
private Integer port;
}
其中的@ConfigurationProperties註解 前面提到過,在pom中,其中屬性值配置在yml文件中,以下(具體內容根據本身的需求來定):
到這裏就能夠開始測試了,能夠在本地啓動兩個服務(一個服務也行),根據本身controller裏面的訪問路徑配置httpclientconfigure,而後直接調用本身controller裏方法便可。
以個人demo爲例,調用者controller代碼以下:
@GetMapping
@RequestMapping("/doGetHaveNoParam")
public void doGetHaveNoParam(){
httpClientUtil.doGetHttp(null,false);
}
@GetMapping
@RequestMapping("/doGetHaveParam")
public void doGetHaveParam(){
System.out.println("調用有參Get請求,當前時間:"+System.currentTimeMillis());
List params = new ArrayList<>();
params.add(new BasicNameValuePair("name", "&"));
params.add(new BasicNameValuePair("age", "22"));
httpClientUtil.doGetHttp(params,true);
}
@PostMapping
@RequestMapping("/doPostHaveNoParam")
public void doPostHaveNoParam(){
httpClientUtil.doPostHttp(null,false);
}
@PostMapping
@RequestMapping("/doPostHaveParam")
public void doPostHaveParam(){
httpClientUtil.doPostHttp(new User("name",11),true);
}
被調用者controller代碼以下:
@RequestMapping("/doGetHaveNoParam")
public String doGetHaveNoParam(){
return "doGetHaveNoParam successful";
}
@RequestMapping("/doGetHaveParam")
public List doGetHaveParam(String name,Integer age){
return getUserByAge(name,age);
}
@PostMapping
@RequestMapping("/doPostHaveNoParam")
public String doPostHaveNoParam(){
return "doPostHaveNoParam successful";
}
@PostMapping
@RequestMapping("/doPostHaveParam")
public String doHttpPostParam(@RequestBody User user){
return "do Post params:name="+user.getName()+",age="+user.getAge();
使用postman測試以下:
請求路徑分別爲:
http://localhost:8081/user/doGetHaveNoParam
http://localhost:8081/user/doGetHaveParam
http://localhost:8081/user/doPostHaveNoParam
http://localhost:8081/user/doPostHaveParam
響應結果