在web服务中,调度远程url是常见的使用场景,最初多采用原生的HttpClient,现采用Spring整合的RestTemplate工具类进行.实操如下:
1. 配置
主要用以配置远程链接的相关参数.
@Configuration
public class RestTemplateConfig { @Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
} @Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
factory.setReadTimeout(5000);
return factory;
} }
2.实际使用
此处以post请求为例,使用RestTemplate时主要有以下三种方式:postForObject/postForEntity/exchange
@Autowired
private RestTemplate template; String url = "http://192.168.2.40:8081/channel/channelHourData/getHourNewUserData";
// 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add("dt", "20180416"); // 1、使用postForObject请求接口
String result = template.postForObject(url, paramMap, String.class);
System.out.println("result1==================" + result); // 2、使用postForEntity请求接口
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
ResponseEntity<String> response2 = template.postForEntity(url, httpEntity, String.class);
System.out.println("result2====================" + response2.getBody()); // 3、使用exchange请求接口
ResponseEntity<String> response3 = template.exchange(url, HttpMethod.POST, httpEntity, String.class);
System.out.println("result3====================" + response3.getBody());
3.实操演示
昨日在与其它服务做对接数据时,发现对方实际接收数据有误,换了几种请求方式,要么就是编码有误/要么就是请求体展示有误,随着问题排查的深入,还出现了框架层面报错类转换异常的问题
代码如下 :
// 发送请求 String url = callback; HttpHeaders requestHeaders = new HttpHeaders();
//requestHeaders.add("Content-Type","application/x-www-form-urlencoded");
requestHeaders.add("charset","UTF-8");
requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED); LinkedMultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
paramMap.add("message","Ok");
paramMap.add("code","200");
paramMap.add("data",data.toJSONString()); HttpEntity<LinkedMultiValueMap<String,Object>> httpEntity = new HttpEntity<>(paramMap, requestHeaders); ResponseEntity<String> exchange = restTemplate.postForEntity(url,httpEntity,String.class); String resultRemote = exchange.getBody();
注意事项:
1.与接口方约定好请求头信息 , 如 此处的媒体类型值即为 : application/x-www-form-urlencoded
2.在使用HttpEntity时,注意请求体,value需为String类型.原因在于:Spring框架在遍历请求体参数时,会强转为String,故此处code设置为 "200"