欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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