配置bean:
@Bean(name="agvRestTemplate")
public RestTemplate agvRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
//重点:用于将JSON、application/octet-stream
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
return restTemplate;
}
注入
@Autowired
@Qualifier(value = "agvRestTemplate")
RestTemplate agvRestTemplate;
String url = agvResource.getCallmaterial();
Map param = new HashMap();
param.put("orderId", agvLog.getOrderId());
Map params = new HashMap();
params.put("call_request", param);
//postForObject(url,param1,ClassName),url:请求地址,param1:请求参数 ClassName请求参数对应的实体类名。
//postForObject主要是将请求参数转化为HttpEntity对象
//url为String类型,会自动转换成encodedurl,为java.net.URI,会进一步encoded,画蛇添足[1]
Map result = agvRestTemplate.postForObject(url, params, Map.class);
//getForObject(url,respType,MapVariables),respType:响应数据的类型,MapVariables:urlvariable参数,Map类型,key值需对应url中的变量
//url:http://127.0.0.1:8080/agv/require?order_id={orderId},注意orderId
Map result = agvRestTemplate.postForObject(url, params, Map.class);
【1】:出处