繁体   English   中英

如何通过Spring RestTemplate更改获取请求中的响应http标头?

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

我有用于创建对象的简单java spring方法

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

但是服务器以错误的Content-Type响应我JSON字符串 text / plain而不是application / json (在Postman中检查)。 我得到一个例外:

无法提取响应:找不到适合于响应类型[类地址]和内容类型[text / plain; charset = utf-8]的HttpMessageConverter

所以我想,我需要将响应头Content-Type更改为正确的application / json ,以便MappingJackson2HttpMessageConverter找出JSON字符串并运行代码。

经过一个小时的尝试,我找到了一种简便的方法。

默认情况下,Json转换器仅支持“ application / json ”。 我们只是重写它以支持“ 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);

谢谢你的帮助! 万一我不能更改响应的标题。 我用正确的标题创建新的响应对象。

            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());
            }

我敢肯定这不是一个简单且好的解决方案,但它确实有效。

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

    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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM