Spring-boot Resttemplate response.body is null while interceptor clearly shows body

為{幸葍}努か 提交于 2020-08-23 06:45:10

问题


With Spring-boot 1.5.10.RELEASE, I am getting response.body as null.

Here is how I am using RestTemplate

RestTemplate restTemplate = new RestTemplate();
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
    interceptors.add(new LoggingRequestInterceptor());
    restTemplate.setInterceptors(interceptors);

    String url = "http://someurl/Commands";

    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("cmd", "{\"operation\":\"getSomeDetails\"}}");

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);

    ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

    System.out.println("This is always null: " + response.getBody());

While above program always prints null, following interceptor prints valid response body

public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {

final static Logger log = LoggerFactory.getLogger(LoggingRequestInterceptor.class);

@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
                                    final ClientHttpRequestExecution execution) throws IOException {
    traceRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    traceResponse(response);
    return response;
}


private void traceResponse(ClientHttpResponse response) throws IOException {
    StringBuilder inputStringBuilder = new StringBuilder();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
    String line = bufferedReader.readLine();
    while (line != null) {
        inputStringBuilder.append(line);
        inputStringBuilder.append('\n');
        line = bufferedReader.readLine();
    }
    log.debug("============================response begin==========================================");
    log.debug("Status code  : {}", response.getStatusCode());
    log.debug("Status text  : {}", response.getStatusText());
    log.debug("Headers      : {}", response.getHeaders());
    log.debug("Response body: {}", inputStringBuilder.toString());
    log.debug("=======================response end=================================================");
}

}


回答1:


You're consuming the response body in traceResponse; that's your problem. Also, please update your question to be specific; "all latest" means nothing. What's latest today isn't so tomorrow.




回答2:


Although the accepted answer has the reason, I believe the solution is also necessary.

Spring has a BufferingClientHttpRequestFactory that acts as a wrapper to Rest Template's default SimpleClientHttpRequestFactory. It can be passed to a Rest Template during creation. This forces the Rest Template to make interceptors use a copy of the response rather than destroying it.

ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());

RestTemplate restTemplate = new RestTemplate(factory);

Source : http://objectpartners.com/2018/03/01/log-your-resttemplate-request-and-response-without-destroying-the-body/




回答3:


Below code will resolve issue.

@Bean public RestTemplate restTemplate() {
final RestTemplate restTempate = new RestTemplate(new BufferingClientHttpRequestFactory(new
                  SimpleClientHttpRequestFactory()));
final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new LogHttpInterceptor());
restTempate.setInterceptors(interceptors);
return restTemplate;}

While log interceptor will be like below

public class LogHttpInterceptor implements ClientHttpRequestInterceptor {

final static Logger log = LoggerFactory.getLogger(LogHttpInterceptor.class);

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    traceRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    traceResponse(response);
    return response;
}

private void traceRequest(HttpRequest request, byte[] body) throws IOException {
    log.info("===========================================================================request begin");
    log.debug("URI         : {}", request.getURI());
    log.debug("Method      : {}", request.getMethod());
    log.debug("Headers     : {}", request.getHeaders() );
    log.debug("Request body: {}", new String(body, "UTF-8"));
    log.info("=============================================================================request end");
}

private void traceResponse(ClientHttpResponse response) throws IOException {
    StringBuilder inputStringBuilder = new StringBuilder();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
    String line = bufferedReader.readLine();
    while (line != null) {
        inputStringBuilder.append(line);
        inputStringBuilder.append('\n');
        line = bufferedReader.readLine();
    }
    log.info("==========================================================================response begin");
    log.debug("Status code  : {}", response.getStatusCode());
    log.debug("Status text  : {}", response.getStatusText());
    log.debug("Headers      : {}", response.getHeaders());
    log.debug("Response body: {}", inputStringBuilder.toString());
    log.info("===========================================================================response end");
}

Let me know if doesn't work




回答4:


Create your RestTemplate like this

@Bean
    public RestTemplate interceptedRestTemplate() {
        RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(
                new SimpleClientHttpRequestFactory()
        ));
        restTemplate.setInterceptors(List.of(<i>your interceptor</i>));
        return restTemplate;
    }

worked for me.



来源:https://stackoverflow.com/questions/49062866/spring-boot-resttemplate-response-body-is-null-while-interceptor-clearly-shows-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!