要调用的接口服务名:TestA
@RequestMapping(value = "/hi", method = RequestMethod.POST)
@ResponseBody
public String hi(@RequestParam String serviceName,@RequestParam String serviceValue){
return serviceName+" "+serviceValue;
}
服务:TestB使用RestTemplate调用服务TestA接口
@RequestMapping(value = "/api/test")
@ResponseBody
public String order() throws InterruptedException {
MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
param.add("serviceName", "serviceName");
param.add("serviceValue", "serviceValue");
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded");
HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<MultiValueMap<String, Object>>(param, headers);
//含有请求头
String result = restTemplate.postForObject("http://127.0.0.1:9003/hi", formEntity, String.class);
//不含请求头
// String result = restTemplate.postForObject("http://127.0.0.1:9003/hi", param, String.class);
return result;
}
使用注意:
1.加上@ResponseBody
2.MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
注意使用是org.springframework.util.MultiValueMap包里的MultiValueMap
3.RestTemplate会对请求头判断,会更具请求头不通走不同的逻辑。默认是 text/html
如果是 application/x-www-form-urlencoded 这个请求头 会对数据镜像 url 编码。
不可以传递 非 字符串类型的数据!
4.String result = restTemplate.postForObject("http://127.0.0.1:9003/hi", formEntity, String.class);
如果使用的ip访问,那么不需要加@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
String result = restTemplate.postForObject("http://TestA/hi", formEntity, String.class);
如果使用是服务名访问,那么需要加上@LoadBalanced
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}