您的位置:首页 > 其它

使用restTemplate调用外部接口

2017-08-05 19:19 591 查看
前提:两个服务注册到一个注册中心上面
1:在Main.class中加入@EnableDiscoveryClient注解
2:在Main.Class中加入如下代码,提供restTemplate对象
@Bean@LoadBalancedRestTemplate restTemplate() {return new RestTemplate();}
3:在controller中调用外部接口
Map<String, Object> map = new HashMap<String, Object>();//map中传递参数
map.put("page", 1);map.put("pageSize", 10);String requestJson = net.sf.json.JSONObject.fromObject(map).toString();HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<String> entities = new HttpEntity<String>(requestJson,headers);
String result = restTemplate.postForObject("调用外部接口的地址",entities,String.class);//这里的调用最好加入异常处理

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: