如何用spring-boot集成httpClient實現(xiàn)遠程調(diào)用?這篇文章運用了實例代碼展示,代碼非常詳細,可供感興趣的小伙伴們參考借鑒,希望對大家有所幫助。
創(chuàng)新互聯(lián)堅持“要么做到,要么別承諾”的工作理念,服務領域包括:成都做網(wǎng)站、成都網(wǎng)站建設、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣等服務,滿足客戶于互聯(lián)網(wǎng)時代的黃埔網(wǎng)站設計、移動媒體設計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡建設合作伙伴!
引入相關依賴:
org.apache.httpcomponents
httpclient
4.5.9
com.alibaba
fastjson
1.2.47
org.springframework.boot
spring-boot-configuration-processor
true
創(chuàng)建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();
// 參數(shù)
URI uri = null;
try {
// 設置uri信息,并將參數(shù)集合放入uri;
if(haveParams){//有參調(diào)用
uri = new URIBuilder().setScheme(httpClientConfigure.getScheme()).setHost(httpClientConfigure.getHost())
.setPort(httpClientConfigure.getPort()).setPath(httpClientConfigure.getMapPath().get("interface2"))
.setParameters(params).build();
}else{//無參調(diào)用
uri = new URIBuilder().setScheme(httpClientConfigure.getScheme()).setHost(httpClientConfigure.getHost())
.setPort(httpClientConfigure.getPort()).setPath(httpClientConfigure.getMapPath().get("interface1"))
.build();
}
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
// 創(chuàng)建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);
// 由客戶端執(zhí)行(發(fā)送)Get請求
response = httpClient.execute(httpGet);
// 從響應模型中獲取響應實體
HttpEntity responseEntity = response.getEntity();
System.out.println("響應狀態(tài)為:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("響應內(nèi)容長度為:" + responseEntity.getContentLength());
System.out.println("響應內(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();
}
}
}
/**
* @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信息,并將參數(shù)集合放入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();
}
// 創(chuàng)建Post請求
HttpPost httpPost = new HttpPost(uri);
if(haveParam){
//入?yún)?/p>
// 利用阿里的fastjson,將Object轉(zhuǎn)換為json字符串;
// (需要導入com.alibaba.fastjson.JSON包)
String jsonString = JSON.toJSONString(user);
StringEntity entity = new StringEntity(jsonString, "UTF-8");
// post請求是將參數(shù)放在請求體里面?zhèn)鬟^去的;這里將entity放入post請求體中
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
}
// 響應模型
CloseableHttpResponse response = null;
try {
// 由客戶端執(zhí)行(發(fā)送)Post請求
response = httpClient.execute(httpPost);
// 從響應模型中獲取響應實體
HttpEntity responseEntity = response.getEntity();
System.out.println("響應狀態(tài)為:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("響應內(nèi)容長度為:" + responseEntity.getContentLength());
System.out.println("響應內(nèi)容為:" + EntityUtils.toString(responseEntity));
}鄭州婦科醫(yī)院哪家好 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文件中,如下(具體內(nèi)容根據(jù)自己的需求來定):
到這里就可以開始測試了,可以在本地啟動兩個服務(一個服務也行),根據(jù)自己controller里面的訪問路徑配置httpclientconfigure,然后直接調(diào)用自己controller里方法即可。
以我的demo為例,調(diào)用者controller代碼如下:
@GetMapping
@RequestMapping("/doGetHaveNoParam")
public void doGetHaveNoParam(){
httpClientUtil.doGetHttp(null,false);
}
@GetMapping
@RequestMapping("/doGetHaveParam")
public void doGetHaveParam(){
System.out.println("調(diào)用有參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);
}
被調(diào)用者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
以上就是用spring-boot集成httpClient實現(xiàn)遠程調(diào)用的方法,代碼詳細清楚,如果在日常工作遇到這個問題,希望你能通過這篇文章解決問題。如果想了解更多相關內(nèi)容,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
當前文章:如何用spring-boot集成httpClient實現(xiàn)遠程調(diào)用
網(wǎng)頁網(wǎng)址:http://jinyejixie.com/article36/pphosg.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供自適應網(wǎng)站、移動網(wǎng)站建設、定制開發(fā)、網(wǎng)站制作、定制網(wǎng)站、手機網(wǎng)站建設
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)