前言
SpringBoot不仅保留了Spring框架原有的卓越特性,还通过简化配置极大地促进了Spring应用的构建与开发流程。在Spring Boot项目开发过程中,常常会遇到本模块代码需要访问外部模块接口或外部URL链接的需求,例如,在APaaS(应用程序平台即服务)开发时,需要封装接口以调用APaaS提供的接口(如发起流程的submit接口等)。针对此类需求,以下提供了三种方案(在不使用Dubbo的情况下)供我们选择。
一、httpClient请求
/*
* @description get方式获取入参,插入数据并发起流程
*/
@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调用外部接口
*/
public static 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) {
throw new RuntimeException(e);
}
return jsonObject;}
二、RestTemplate方法
Spring-Boot开发中,RestTemplate同样为外部访问提供了接口API,
Get请求方式
提供了getForObject 、getForEntity两种方式,其中getForEntity如下三种方法的实现:
Get–getForEntity,两种方式重载
1.getForEntity(Stringurl,Class responseType,Object…urlVariables)
2.getForEntity(URI url,Class responseType)
Get–getForEntity(URI url,Class responseType)
//该方法使用URI对象来替代之前的url和urlVariables参数来指定访问地址和参数绑定。URI是JDK java.net包下的一个类,表示一个统一资源标识符(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();
ResponseEntityresponseEntity=restTemplate.getForEntity(uri,String.class).getBody();
Get–getForEntity(Stringurl,Class responseType,Object…urlVariables)
//该方法提供了三个参数,其中url为请求的地址,responseType为请求响应body的包装类型,urlVariables为url中的参数绑定,该方法的参考调用如下:
// http://USER-SERVICE/user?name={name)
RestTemplate restTemplate=new RestTemplate();
Mapparams=new HashMap<>();
params.put("name","dada"); //
ResponseEntityresponseEntity=restTemplate.getForEntity("http://USERSERVICE/user?name={name}",String.class,params);
Get–getForObject三种方式重载
1.getForObject(String url,Class responseType,Object...urlVariables)
2.getForObject(String url,Class responseType,Map urlVariables)
3.getForObject(URI url,Class responseType)
Post 请求方式
Post请求提供了三种方式:postForEntity、postForObject和postForLocation,且每种方式都包含具体的实现方法。接下来,我们将详细介绍postForEntity的使用方法。
Post–postForEntity,三种方式重载
1.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方式获取入参,插入数据并发起流程
*/
@PostMapping("/submit2")
public Object insertFinanceCompensation(@RequestBody JSONObject jsonObject) {
String documentId=jsonObject.get("documentId").toString();
return task2Service.submit(documentId);
}
/*
* @description 使用restTimeplate调外部接口
*/
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();}
四、使用Feign进行消费
项目中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
启动类上添加@EnableFeignClients
@SpringBootApplication
@EnableFeignClients
@ComponentScan(basePackages = {"com.definesys.mpaas", "com.xdap.*" ,"com.xdap.*"})
public class MobilecardApplication {
public static void main(String[] args) {
SpringApplication.run(MobilecardApplication.class, args);
}
}
定义controller
@Autowired
PrintService printService;
@PostMapping("/outSide")
public String test(@RequestBody TestDto testDto) {
return printService.print(testDto);
}
定义service
@Service
public interface PrintService {
public String print(TestDto testDto);
}
serviceImpl
public class PrintServiceImpl implements PrintService {
@Override
public String print(TestDto testDto) {
return "模拟外部系统的接口功能"+testDto.getId();
}
}
定义controller
@Autowired
FeignService2 feignService2;
//测试feign调用外部接口入口
@PostMapping("/test2")
public String test2(@RequestBody TestDto testDto) {
return feignService2.getMessage(testDto);
}