Spring Boot 调用外部接口的 3 种方式,还有谁不会?!
1、简介
SpringBoot不仅继承了Spring框架原有的优秀特性,而且还通过简化配置来进一步简化了Spring应用的整个搭建和开发过程。在Spring-Boot项目开发中,存在着本模块的代码需要访问外面模块接口,或外部url链接的需求, 比如在apaas开发过程中需要封装接口在接口中调用apaas提供的接口(像发起流程接口submit等等)下面也是提供了三种方式(不使用dubbo的方式)供我们选择
2、方式一:使用原始httpClient请求
/*
* @description get方式获取入参,插入数据并发起流程
* @author lyx
* @date 2022/8/24 16:05
* @params documentId
* @return String
*/
//@RequestMapping(
"/submit/{documentId}")
public String submit1(@PathVariable String documentId)throws ParseException {
//此处将要发送的数据转换为json格式字符串 Map<String,Object> map =task2Service.getMap(documentId);
String jsonStr = JSON.toJSONString(map, SerializerFeature.WRITE_MAP_NULL_FEATURES,SerializerFeature.QuoteFieldNames);
JSONObject jsonObject = JSON.parseObject(jsonStr);
JSONObject sr = task2Service.doPost(jsonObject);
return sr.toString();
}
/*
* @description 使用原生httpClient调用外部接口
* @author lyx
* @date 2022/8/24 16:08
* @params date
* @return JSONObject
*/
publicstatic JSONObject doPost(JSONObject date){
String assessToken=
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ4ZGFwYXBwaWQiOiIzNDgxMjU4ODk2OTI2OTY1NzYiLCJleHAiOjE2NjEyMjY5MDgsImlhdCI6MTY2MTIxOTcwOCwieGRhcHRlbmFudGlkIjoiMzAwOTgxNjA1MTE0MDUyNjA5IiwieGRhcHVzZXJpZCI6IjEwMDM0NzY2MzU4MzM1OTc5NTIwMCJ9.fZAO4kJSv2rSH0RBiL1zghdko8Npmu_9ufo6Wex_TI2q9gsiLp7XaW7U9Cu7uewEOaX4DTdpbFmMPvLUtcj_sQ";
CloseableHttpClient client = HttpClients.createDefault();
// 要调用的接口url String url =
"http://39.103.201.110:30661 /xdap-open/open/process/v1/submit";
HttpPost post =
new HttpPost(url);
JSONObject jsonObject =
null;
try {
//创建请求体并添加数据 StringEntity s =
new StringEntity(date.toString());
//此处相当于在header里头添加content-type等参数 s.setContentType(
"application/json");
s.setContentEncoding(
"UTF-8");
post.setEntity(s);
//此处相当于在Authorization里头添加Bear token参数信息 post.addHeader(
"Authorization",
"Bearer " +assessToken);
HttpResponse res = client.execute(post);
String response1 = EntityUtils.toString(res.getEntity());
if (res.getStatusLine()
.getStatusCode() == HttpStatus.SC_OK) {
// 返回json格式: String result = EntityUtils.toString(res.getEntity());
jsonObject = JSONObject.parseObject(result);
}
}
catch (Exception e) {
thrownew RuntimeException(e);
}
return jsonObject;
}
3、方式二:使用RestTemplate方法
Spring-Boot开发中,RestTemplate同样提供了对外访问的接口API,这里主要介绍Get和Post方法的使用。
Get请求
提供了getForObject
、getForEntity
两种方式,其中getForEntity
如下三种方法的实现:
Get--getForEntity
,存在以下两种方式重载.getForEntity(Stringurl,Class responseType,Object…urlVariables)
2.getForEntity(URI url,Class responseType)
Get--getForEntity(URI url,Class responseType)
RestTemplate restTemplate=
new RestTemplate();
UriComponents
uriComponents=UriComponentsBuilder.fromUriString(
"http://USER-SERVICE/user?name={name}")
.build()
.expand(
"dodo")
.encode();
URI uri=uriComponents.toUri();
ResponseEntityresponseEntity=restTemplate.getForEntity(uri,String
.class).getBody();
Get--getForEntity(Stringurl,Class responseType,Object…urlVariables)
RestTemplate restTemplate=
new RestTemplate();
Mapparams=
new HashMap<>();
params.put(
"name",
"dada");
//ResponseEntityresponseEntity=restTemplate.getForEntity(
"http://USERSERVICE/user?name={name}",String
.class,params);
.getForObject(String url,Class responseType,Object...urlVariables)
2.getForObject(String url,Class responseType,Map urlVariables)
3.getForObject(URI url,Class responseType)
Post 请求
.postForEntity(String url,Object request,Class responseType,Object... uriVariables)
2.postForEntity(String url,Object request,Class responseType,Map uriVariables)
3.postForEntity(URI url,Object request,Class responseType)
/*
* @description post方式获取入参,插入数据并发起流程
* @author lyx
* @date 2022/8/24 16:07
* @params
* @return
*/
@PostMapping(
"/submit2")
public Object insertFinanceCompensation(@RequestBody JSONObject jsonObject){
String documentId=jsonObject.get(
"documentId").toString();
return task2Service.submit(documentId);
}
/*
* @description 使用restTimeplate调外部接口
* @author lyx
* @date 2022/8/24 16:02
* @params documentId
* @return String
*/
public String submit(String documentId){
String assessToken=
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ4ZGFwYXBwaWQiOiIzNDgxMjU4ODk2OTI2OTY1NzYiLCJleHAiOjE2NjEyMjY5MDgsImlhdCI6MTY2MTIxOTcwOCwieGRhcHRlbmFudGlkIjoiMzAwOTgxNjA1MTE0MDUyNjA5IiwieGRhcHVzZXJpZCI6IjEwMDM0NzY2MzU4MzM1OTc5NTIwMCJ9.fZAO4kJSv2rSH0RBiL1zghdko8Npmu_9ufo6Wex_TI2q9gsiLp7XaW7U9Cu7uewEOaX4DTdpbFmMPvLUtcj_sQ";
RestTemplate restTemplate =
new RestTemplate();
//创建请求头 HttpHeaders httpHeaders =
new HttpHeaders();
//此处相当于在Authorization里头添加Bear token参数信息 httpHeaders.add(HttpHeaders.AUTHORIZATION,
"Bearer " + assessToken);
//此处相当于在header里头添加content-type等参数 httpHeaders.add(HttpHeaders.CONTENT_TYPE,
"application/json");
Map<String, Object> map = getMap(documentId);
String jsonStr = JSON.toJSONString(map);
//创建请求体并添加数据 HttpEntity<Map> httpEntity =
new HttpEntity<Map>(map, httpHeaders);
String url =
"http://39.103.201.110:30661/xdap-open/open/process/v1/submit";
ResponseEntity<String> forEntity = restTemplate.postForEntity(url,httpEntity,String
.class);
//此处三个参数分别是请求地址、请求体以及返回参数类型return forEntity.toString();
}
4、方式三:使用Feign进行消费
在maven项目中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>
1.2.2.RELEASE</version>
</dependency>
(basePackages = {
"com.definesys.mpaas",
"com.xdap.*" ,
"com.xdap.*"})
publicclassMobilecardApplication{
publicstaticvoidmain(String[] args){
SpringApplication.run(MobilecardApplication
.class, args);
}
}
PrintService printService;
@PostMapping(
"/outSide")
public String test(@RequestBody TestDto testDto){
return printService.print(testDto);
}
{
public String print(TestDto testDto);
}
{
@Overridepublic String print(TestDto testDto){
return"模拟外部系统的接口功能"+testDto.getId();
}
}
(url =
"${outSide.url}", name =
"service2")
publicinterfaceFeignService2{
@RequestMapping(value =
"/custom/outSide", method = RequestMethod.POST)
@ResponseBodypublic String getMessage(@Valid @RequestBody TestDto testDto);
}
FeignService2 feignService2;
//测试feign调用外部接口入口@PostMapping(
"/test2")
public String test2(@RequestBody TestDto testDto){
return feignService2.getMessage(testDto);
}
添加Header解决方法
{
@Overridepublicvoidapply(RequestTemplate requestTemplate){
//添加token requestTemplate.header(
"token",
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ4ZGFwYXBwaWQiOiIzNDgxMjU4ODk2OTI2OTY1NzYiLCJleHAiOjE2NjEyMjY5MDgsImlhdCI6MTY2MTIxOTcwOCwieGRhcHRlbmFudGlkIjoiMzAwOTgxNjA1MTE0MDUyNjA5IiwieGRhcHVzZXJpZCI6IjEwMDM0NzY2MzU4MzM1OTc5NTIwMCJ9.fZAO4kJSv2rSH0RBiL1zghdko8Npmu_9ufo6Wex_TI2q9gsiLp7XaW7U9Cu7uewEOaX4DTdpbFmMPvLUtcj_sQ");
}
}
(url =
"${outSide.url}",name =
"feignServer", configuration = FeignDemoConfig
.
class)
publicinterfaceTokenDemoClient
{
@RequestMapping(value =
"/custom/outSideAddToken", method = RequestMethod.POST)
@ResponseBodypublic String getMessage(@Valid @RequestBody TestDto testDto);
}
(
"/testToken")
public String test4(@RequestBody TestDto testDto){
return tokenDemoClient.getMessage(testDto);
}
更多好文章
关键词
方法
接口
数据
参数
种方式
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。