Spring-Boot 訪問(wèn)外部接口的方案總結(jié)
一、簡(jiǎn)介
在Spring-Boot項(xiàng)目開發(fā)中,存在著本模塊的代碼需要訪問(wèn)外面模塊接口,或外部url鏈接的需求,針對(duì)這一需求目前存在著三種解決方案,下面將對(duì)這三種方案進(jìn)行整理和說(shuō)明。
二、Spring-Boot項(xiàng)目中訪問(wèn)外部接口
2.1 方案一 采用原生的Http請(qǐng)求
在代碼中采用原生的http請(qǐng)求,代碼參考如下:
@RequestMapping("/doPostGetJson")
public String doPostGetJson() throws ParseException {
//此處將要發(fā)送的數(shù)據(jù)轉(zhuǎn)換為json格式字符串
String jsonText = "{id:1}";
JSONObject json = (JSONObject) JSONObject.parse(jsonText);
JSONObject sr = this.doPost(json);
System.out.println("返回參數(shù):" + sr);
return sr.toString();
}
public static JSONObject doPost(JSONObject date) {
HttpClient client = HttpClients.createDefault();
// 要調(diào)用的接口方法
String url = "http://192.168.1.101:8080/getJson";
HttpPost post = new HttpPost(url);
JSONObject jsonObject = null;
try {
StringEntity s = new StringEntity(date.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
post.addHeader("content-type", "text/xml");
HttpResponse res = client.execute(post);
String response1 = EntityUtils.toString(res.getEntity());
System.out.println(response1);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
jsonObject = JSONObject.parseObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return jsonObject;
}2.2 方案二 采用Feign進(jìn)行消費(fèi)
1、在maven項(xiàng)目中添加依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.2.2.RELEASE</version> </dependency>
2、編寫接口,放置在service層
@FeignClient(url = "${decisionEngine.url}",name="engine")
public interface DecisionEngineService {
@RequestMapping(value="/decision/person",method= RequestMethod.POST)
public JSONObject getEngineMesasge(@RequestParam("uid") String uid,@RequestParam("productCode") String productCode);
}這里的decisionEngine.url 是配置在properties中的 是ip地址和端口號(hào)
decisionEngine.url=http://10.2.1.148:3333
/decision/person 是接口名字
3、在Java的啟動(dòng)類上加上@EnableFeignClients
@EnableFeignClients //參見(jiàn)此處
@EnableDiscoveryClient
@SpringBootApplication
@EnableResourceServer
public class Application implements CommandLineRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
@Autowired
private AppMetricsExporter appMetricsExporter;
@Autowired
private AddMonitorUnitService addMonitorUnitService;
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}4、在代碼中調(diào)用接口即可
@Autowired
private DecisionEngineService decisionEngineService ;
decisionEngineService.getEngineMesasge("uid" , "productCode");2.3、方案三 采用RestTemplate方法
在Spring-Boot開發(fā)中,RestTemplate同樣提供了對(duì)外訪問(wèn)的接口API,這里主要介紹Get和Post方法的使用。Get請(qǐng)求提供了兩種方式的接口getForObject 和 getForEntity,getForEntity提供如下三種方法的實(shí)現(xiàn)。
Get請(qǐng)求之——getForEntity(Stringurl,Class responseType,Object…urlVariables)
該方法提供了三個(gè)參數(shù),其中url為請(qǐng)求的地址,responseType為請(qǐng)求響應(yīng)body的包裝類型,urlVariables為url中的參數(shù)綁定,該方法的參考調(diào)用如下:
//http://USER-SERVICE/user?name={1}
getForEntity("http://USER-SERVICE/user?name={1}",String.class,"didi")
Get請(qǐng)求之——getForEntity(String url,Class responseType,Map urlVariables)
該方法提供的參數(shù)中urlVariables的參數(shù)類型使用了Map類型,因此在使用該方法進(jìn)行參數(shù)綁定時(shí)需要在占位符中指定Map中參數(shù)的key值,該方法的參考調(diào)用如下:
// http://USER-SERVICE/user?name={name)
RestTemplate restTemplate=new RestTemplate();
Map<String,String> params=new HashMap<>();
params.put("name","dada"); //
ResponseEntity<String> responseEntity=restTemplate.getForEntity("http://USERSERVICE/user?name={name}",String.class,params);Get請(qǐng)求之——getForEntity(URI url,Class responseType)
該方法使用URI對(duì)象來(lái)替代之前的url和urlVariables參數(shù)來(lái)指定訪問(wèn)地址和參數(shù)綁定。URI是JDK java.net包下的一個(gè)類,表示一個(gè)統(tǒng)一資源標(biāo)識(shí)符(Uniform Resource Identifier)引用。參考如下:
RestTemplate restTemplate=new RestTemplate();
UriComponents uriComponents=UriComponentsBuilder.fromUriString(
"http://USER-SERVICE/user?name={name}")
.build()
.expand("dodo")
.encode();
URI uri=uriComponents.toUri();
ResponseEntity<String> responseEntity=restTemplate.getForEntity(uri,String.class).getBody();Get請(qǐng)求之——getForObject
getForObject方法可以理解為對(duì)getForEntity的進(jìn)一步封裝,它通過(guò)HttpMessageConverterExtractor對(duì)HTTP的請(qǐng)求響應(yīng)體body內(nèi)容進(jìn)行對(duì)象轉(zhuǎn)換,實(shí)現(xiàn)請(qǐng)求直接返回包裝好的對(duì)象內(nèi)容。getForObject方法有如下:
getForObject(String url,Class responseType,Object...urlVariables) getForObject(String url,Class responseType,Map urlVariables) getForObject(URI url,Class responseType)
Post請(qǐng)求提供有三種方法,postForEntity、postForObject和postForLocation。其中每種方法都存在三種方法,postForEntity方法使用如下:
RestTemplate restTemplate=new RestTemplate();
User user=newUser("didi",30);
ResponseEntity<String> responseEntity=restTemplate.postForEntity("http://USER-SERVICE/user",user,String.class); //提交的body內(nèi)容為user對(duì)象,請(qǐng)求的返回的body類型為String
String body=responseEntity.getBody();postForEntity存在如下三種方法的重載
postForEntity(String url,Object request,Class responseType,Object... uriVariables) postForEntity(String url,Object request,Class responseType,Map uriVariables) postForEntity(URI url,Object request,Class responseType)
postForEntity中的其它參數(shù)和getForEntity的參數(shù)大體相同在此不做介紹。
參考文獻(xiàn)
1.淺析SpringBoot微服務(wù)中異步調(diào)用數(shù)據(jù)提交數(shù)據(jù)庫(kù)的問(wèn)題
2.spring boot 常見(jiàn)http請(qǐng)求url參數(shù)獲取方法
3.Spring學(xué)習(xí)筆記之RestTemplate使用小結(jié)
4.Spring RestTemplate中幾種常見(jiàn)的請(qǐng)求方式
5.Springboot使用RestTemplate調(diào)用第三方接口的操作代碼
到此這篇關(guān)于Spring-Boot 訪問(wèn)外部接口的方案總結(jié)的文章就介紹到這了,更多相關(guān)Spring-Boot 訪問(wèn)外部接內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
23種設(shè)計(jì)模式(12)java模版方法模式
這篇文章主要為大家詳細(xì)介紹了23種設(shè)計(jì)模式之java模版方法模式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
詳解springboot-mysql-pagehelper分頁(yè)插件集成
這篇文章主要介紹了springboot-mysql-pagehelper分頁(yè)插件集成,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
mybatis?foreach傳兩個(gè)參數(shù)批量刪除
這篇文章主要介紹了mybatis?foreach?批量刪除傳兩個(gè)參數(shù),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04
java數(shù)據(jù)結(jié)構(gòu)之棧的詳解
這篇文章主要為大家詳細(xì)介紹了Java數(shù)據(jù)結(jié)構(gòu)的棧的應(yīng)用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能給你帶來(lái)幫助2021-08-08
springboot+redis 實(shí)現(xiàn)分布式限流令牌桶的示例代碼
這篇文章主要介紹了springboot+redis 實(shí)現(xiàn)分布式限流令牌桶 ,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Maven默認(rèn)使用JDK1.5的問(wèn)題及解決方案
這篇文章主要介紹了Maven默認(rèn)使用JDK1.5的問(wèn)題及解決方案,本文給大家分享兩種方式,通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04
詳細(xì)介紹Java關(guān)鍵字throw?throws?Throwable的用法與區(qū)別
這篇文章主要介紹了java中throws與throw及Throwable的用法和區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
JavaEE Spring MyBatis如何一步一步實(shí)現(xiàn)數(shù)據(jù)庫(kù)查詢功能
這篇文章主要介紹了JavaEE Spring MyBatis如何一步一步實(shí)現(xiàn)數(shù)據(jù)庫(kù)查詢功能,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08

