如何在Spring ClientHttpRequestInterceptor中修改REST响应头?

时间:2016-07-14 09:41:57

标签: java spring rest resttemplate

使用Spring和RestTemplate我正在尝试调用外部服务,该服务不会返回正确的内容类型作为HTTP响应的一部分。 JSON响应和XML响应都返回Content-Type of text / html。我想使用相同的RestTemplate实例来处理这些请求,并使用适当的HttpMessageConverter处理不同的响应类型。为了做到这一点,我想实现ClientHttpRequestInterceptor,检测内容类型修改响应头如图所示:

@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes,
                                    ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {

    ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);
    InputStream body = response.getBody();
    String bodyString;

    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(body))) {
        bodyString = buffer.lines().collect(Collectors.joining("\n"));
    }

    if (isJson(bodyString)) {
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
    } else if (isXml(bodyString)) {
        response.getHeaders().setContentType(MediaType.APPLICATION_XML);
    } else {
        throw new RuntimeException("Unexpected message type detected in response");
    }

    return response;
}

但是,这会导致以下异常:

Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://xxx.xxxx.xxxxxxx.xxx": stream is closed; nested exception is java.io.IOException: stream is closed

在点击RestTemplate消息转换器之前修改响应头的正确方法是什么?

0 个答案:

没有答案