How to change response http header in get request by spring RestTemplate?

I have simple java spring method for creating object

RestTemplate restTemplate = new RestTemplate();
Address address = restTemplate.getForObject(url, Address.class);

But the server responds me JSON string with wrong Content-Type: text/plain instead of application/json (checked in Postman). And I get the exception:

Could not extract response: no suitable HttpMessageConverter found for response type [class Address] and content type [text/plain;charset=utf-8]

So I think, I need change response header Content-Type to right application/json , that MappingJackson2HttpMessageConverter find out JSON string and run code as well.


After trying for an hour, I found a short and easy way.

Json converter by default supports only "application/json". We just override it to support "text/plain".

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

// support "text/plain"
converter.setSupportedMediaTypes(Arrays.asList(TEXT_PLAIN, APPLICATION_JSON));

RestTemplate template = new RestTemplate();
template.getMessageConverters().add(converter);

// It's ok now
MyResult result = tmp.postForObject("http://url:8080/api", 
            new MyRequest("param value"), MyResult.class);

Thank you for help! In case I can't change response's header. I create new response object with right header.

            ClientHttpRequest clientHttpRequest = new SimpleClientHttpRequestFactory().createRequest(URI.create(str), org.springframework.http.HttpMethod.GET);
            final ClientHttpResponse clientHttpResponse = clientHttpRequest.execute();
            MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
            Address address = new Address();
            //It always true, because service always returns 200 OK
            if (clientHttpResponse.getStatusCode() == HttpStatus.OK) {
                address = (Address) converter.read(address.getClass(), new HttpInputMessage() {
                    public InputStream getBody() throws IOException {
                        return clientHttpResponse.getBody();
                    }

                    public HttpHeaders getHeaders() {
                        HttpHeaders httpHeaders = new HttpHeaders();
                        httpHeaders.putAll(clientHttpResponse.getHeaders());
                        httpHeaders.put("Content-Type", Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
                        return httpHeaders;
                    }
                });
                busStop.setNearestAddress(address.toString());
            }

I'm sure it isn't simple and good solution, but It works.


要为您的请求设置内容类型,您可以执行以下操作:

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity entity = new HttpEntity(headers);
    ResponseEntity<Address> response = restTemplate.exchange(url, HttpMethod.GET,  entity, Address.class);
    Address address = response.getBody();
链接地址: http://www.djcxy.com/p/48188.html

上一篇: 用弹簧启动从Itis中获取Json对象

下一篇: 如何通过spring RestTemplate在获取请求中更改响应http头?