Springboot 调用外部接口的三种方式

1. 简介

在Springboot项目中,存在需要访问外部模块接口,或者外部URL链接的需求,下面就介绍三种调用外部接口的方式(不使用dubbo的方式)

2. 使用原始HttpClient请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@RequestMapping("/submit/{documentId}")
public String submit(@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 = doPost(jsonObject);
return sr.toString();
}
/**
* httpclient请求
*/
public static JSONObject doPost(JSONObject date) {
String assessToken="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ4ZGFwYXBwaWQiOiIzNDgxMjU4ODk2OTI2OTY1NzYiLCJleHAiOjE2NjEyMjY5MDgsImlhdCI6MTY2MTIxOTcwOCwieGRhcHRlbmFudGlkIjoiMzAwOTgxNjA1MTE0MDUyNjA5IiwieGRhcHVzZXJpZCI6IjEwMDM0NzY2MzU4MzM1OTc5NTIwMCJ9.fZAO4kJSv2rSH0RBiL1zghdko8Npmu_9ufo6Wex_TI2q9gsiLp7XaW7U9Cu7uewEOaX4DTdpbFmMPvLUtcj_sQ";
CloseableHttpClient client = HttpClients.createDefault();
// 要调用的接口url
String url = "http://192.1680.96:9091/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;
}

3. 使用RestTemplate方法

在Springboot开发中,RestTemplate同样提供了对外访问的接口API。

3.1. Get请求

提供了getForObjectgetForEntity两种方式,其中getForEntity如下三种方法实现:

  1. getForEntity(URI url, Class responseType)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    //该方法使用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();
  2. getForEntity(Stringurl,Class responseType,Object…urlVariables)
    1
    2
    3
    4
    5
    6
    //该方法提供了三个参数,其中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);

getForObject,存在以下三种方式重载:

1
2
3
getForObject(String url,Class responseType,Object...urlVariables)
getForObject(String url,Class responseType,Map urlVariables)
getForObject(URI url,Class responseType)

getForObject方法可以理解为对getForEntity的进一步封装,它通过HttpMessageConverterExactor对Http请求响应体body内容进行对象转化,实现请求直接返回包装好的对象内容。

3.2. Post请求

ost请求提供有postForEntitypostForObjectpostForLocation三种方式,其中每种方式都有三种方法,下面介绍postForEntity的使用方法。

postForEntity,存在以下三种方式重载:

1
2
3
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)

如下仅演示第二种重载方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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进行消费

  1. 在maven项目中添加依赖

    1
    2
    3
    4
    5
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.4.2.RELEASE</version>
    </dependency>
  2. 在启动类上加上@EnableFeignClients

    1
    2
    3
    4
    5
    6
    7
    @SpringBootApplication
    @EnableFeignClients
    public class ChapterApplication {
    public static void main(String[] args) {
    SpringApplication.run(MobilecardApplication.class, args);
    }
    }

    此处编写接口模拟外部接口供feign调用外部接口方式使用

  1. 定义service以及controller

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @Service
    public interface PrintService {
    public String print(TestDto testDto);
    }
    public class PrintServiceImpl implements PrintService {

    @Override
    public String print(TestDto testDto) {
    return "模拟外部系统的接口功能"+testDto.getId();
    }
    }
    1
    2
    3
    4
    5
    6
    7
    @Autowired
    PrintService printService;

    @PostMapping("/outSide")
    public String test(@RequestBody TestDto testDto) {
    return printService.print(testDto);
    }
  2. 定义FeignService

    1
    2
    3
    4
    5
    6
    7
    8
    //此处name需要设置不为空,url需要在.properties中设置
    @Service
    @FeignClient(url = "${outSide.url}", name = "service2")
    public interface FeignService {
    @RequestMapping(value = "/custom/outSide", method = RequestMethod.POST)
    @ResponseBody
    public String getMessage(@Valid @RequestBody TestDto testDto);
    }
  3. 定义调用Controller

    1
    2
    3
    4
    5
    6
    7
    @Autowired
    FeignService feignService;
    //测试feign调用外部接口入口
    @PostMapping("/test")
    public String test(@RequestBody TestDto testDto) {
    return feignService.getMessage(testDto);
    }
  4. postman测试

4.1. 补充信息

添加Header解决方法

将token等信息放入Feign请求头中,主要通过重写RequestInterceptor的apply方法实现

  1. 定义config

    1
    2
    3
    4
    5
    6
    7
    8
    @Configuration
    public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
    //添加token
    requestTemplate.header("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ4ZGFwYXBwaWQiOiIzNDgxMjU4ODk2OTI2OTY1NzYiLCJleHAiOjE2NjEyMjY5MDgsImlhdCI6MTY2MTIxOTcwOCwieGRhcHRlbmFudGlkIjoiMzAwOTgxNjA1MTE0MDUyNjA5IiwieGRhcHVzZXJpZCI6IjEwMDM0NzY2MzU4MzM1OTc5NTIwMCJ9.fZAO4kJSv2rSH0RBiL1zghdko8Npmu_9ufo6Wex_TI2q9gsiLp7XaW7U9Cu7uewEOaX4DTdpbFmMPvLUtcj_sQ");
    }
    }
  2. 定义service

    1
    2
    3
    4
    5
    6
    7
    @Service
    @FeignClient(url = "${outSide.url}",name = "feignServer", configuration = FeignDemoConfig.class)
    public interface TokenDemoClient {
    @RequestMapping(value = "/custom/outSideAddToken", method = RequestMethod.POST)
    @ResponseBody
    public String getMessage(@Valid @RequestBody TestDto testDto);
    }
  3. 定义Controller

    1
    2
    3
    4
    5
    //测试feign调用外部接口入口,加上token
    @PostMapping("/testToken")
    public String test4(@RequestBody TestDto testDto) {
    return tokenDemoClient.getMessage(testDto);
    }

参考作者:Chelsea的文章:Springboot中调用外部接口的三种方式