RestTemplate服务之间传递数据-SpringBoot
一、调用方:
代码
public void put(String url, String paramJson, HttpServletRequest request) throws JsonProcessingException {
HttpEntity<String> requestEntity = setHttpHeader(request, paramJson);
restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class);
}
private HttpEntity<String> setHttpHeader(HttpServletRequest request, String json) throws JsonProcessingException {
String authorization = request.getHeader("Authorization");
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "*/*");
headers.add("Content-Type", "application/json");
headers.add("Authorization", authorization);
return new HttpEntity<>(json, headers);
}
二、被调用方:
代码
public void putTest(@RequestBody String ids) throws IOException {
ObjectMapper mapper = new ObjectMapper();
List<String> beanList = mapper.readValue(ids, new TypeReference<List<String>>() {});
}
三、总结:
1. 对于项目中使用了Spring security,就会对于所有的API都保护起来,没有对应Token,是无法访问的,使用RestTemplate去访问其他的服务的时候,Token不会传递,需要我们对于请求头,再次添加token,才能保证调用数据的正确性。这是刚刚项目中的问题,若有更好的解决方法和问题,请大家包含和提问啦。。。