RestTemplate 发送post请求
程序员文章站
2022-06-24 21:56:21
...
private RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
ExtendMappingJackson2HttpMessageConverter convert
= new ExtendMappingJackson2HttpMessageConverter();
convert.setObjectMapper(new ObjectMapper());
restTemplate.getMessageConverters().add(convert);
return restTemplate;
}
private String post(String url, LinkedMultiValueMap<String, Object> params) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded");
HttpEntity<LinkedMultiValueMap<String, Object>> request = new HttpEntity<>(params, headers);
ResponseEntity<String> result = getRestTemplate().postForEntity(url,
request, String.class);
return result.getBody();
}
--------------------------------------------------------------
public class ExtendMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
public ExtendMappingJackson2HttpMessageConverter() {
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.ALL);
//List<MediaType> mediaTypes = getSupportedMediaTypes();
//mediaTypes.add(MediaType.TEXT_HTML);
setSupportedMediaTypes(mediaTypes);
}
}
上一篇: Java中对时间日期类型进行秒数的相加减