Spring-boot Resttemplate response.body为null,而拦截器清楚显示body

时间:2018-03-02 04:32:54

标签: spring-boot resttemplate

使用Spring-boot 1.5.10.RELEASE,我得到response.body为null。

以下是我使用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());

虽然上面的程序总是打印为null, 以下拦截器打印有效的响应主体

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=================================================");
}

}

4 个答案:

答案 0 :(得分:3)

您正在使用system.Data.Entity.Error中的回复正文;那是你的问题。另外,请将您的问题更新为具体的; “所有最新”都没有意义。今天的最新消息明天不是这样。

答案 1 :(得分:1)

尽管接受的答案是有原因的,但我认为解决方案也是必要的。

Spring有一个BufferingClientHttpRequestFactory,用作Rest模板的默认SimpleClientHttpRequestFactory的包装。 可以在创建过程中将其传递到Rest模板。这会迫使Rest模板使拦截器使用响应的副本,而不是破坏响应。

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

RestTemplate restTemplate = new RestTemplate(factory);

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

答案 2 :(得分:0)

下面的代码将解决问题。

@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;}

日志拦截器如下所示

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

让我知道是否无效

答案 3 :(得分:-1)

像这样创建 RestTemplate

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

为我工作。