Spring RestTemplate,当http状态代码为404时获得垃圾响应

时间:2017-03-29 13:50:56

标签: spring model-view-controller resttemplate

我正在编写一个rest代理(它暴露了API并将调用委托给其他服务器)并且它适用于正常情况以及500 http状态代码,我们从其他客户端获得响应。 但是当我们获得404状态代码时,Rest API服务器返回消息但我们从RestTemplate获取垃圾值。我们需要将相同的响应传递给其他API用户,但无法获得相同的响应。

从REST API服务器返回的消息:

{   “STATUS_CODE”: “0”,   “错误”:{
     “代码”: “404”,      “description”:“找不到来源”     } }

通过RestTemplate客户端获得以下响应:

无法粘贴内容,附加响应的屏幕截图。 Response for Http 404 error 请参阅下面的代码。

@RequestMapping(value = "/api/**")
public @ResponseBody String apiProxy(@RequestBody String body, HttpMethod method, HttpServletRequest request,
        HttpServletResponse response) throws URISyntaxException {
    RestTemplate restTemplate = new RestTemplate(
            new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
    restTemplate.setInterceptors(Collections.singletonList(new RestClientLoggingInterceptor()));
    restTemplate.setErrorHandler(new CustomResponseErrorHandler());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    HttpHeaders httpHeaders = new HttpHeaders();
    Enumeration<String> headers = request.getHeaderNames();
    String headerName = null;
    String headerValue = null;
    while (headers.hasMoreElements()) {
        headerName = headers.nextElement();
        headerValue = request.getHeader(headerName);
        httpHeaders.set(headerName, headerValue);
    }
    HttpEntity<String> httpEntity = new HttpEntity<String>(body, httpHeaders);

    URI uri = new URI(ServerProtocol, null, ServerDomain, Integer.valueOf(ServerPort),
            request.getRequestURI(), request.getQueryString(), null);

    ResponseEntity<String> responseEntity = null;
    try {
        responseEntity = restTemplate.exchange(uri, method, httpEntity, String.class);
    } catch (RestClientResponseException e) {
        response.setStatus(e.getRawStatusCode());
        return e.getResponseBodyAsString();
    }
    response.setStatus(responseEntity.getStatusCode().value());
    return responseEntity.getBody();
}

ResponseErrorHandler Class

   public class CustomResponseErrorHandler extends DefaultResponseErrorHandler {

        private static final Logger logger = LogManager.getLogger(CustomResponseErrorHandler.class);

        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            logger.error("Response error: {} {}", response.getStatusCode(), response.getStatusText());
        }

    }

RestClientLoggingInterceptor类

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
                    throws IOException {
                ClientHttpResponse response = execution.execute(request, body);
                logger.debug("request method:" + request.getMethod());
                logger.debug("request URI:" + request.getURI());
                logger.debug("request headers:" + request.getHeaders());
                logger.debug("request body:" + new String(body, Charset.forName("UTF-8")));
                logger.debug("response status code:" + response.getStatusCode());
                logger.debug("response headers:" + response.getHeaders());
                logger.debug("response body:" + IOUtils.toString(response.getBody(), "UTF-8"));

                return response;
            }

由于

1 个答案:

答案 0 :(得分:0)

Cannot parse gzip encoded response with RestTemplate from Spring-Web

对于同样的问题,这对我很有帮助。你可以尝试一下。