gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:53:10 25 4
gpt4 key购买 nike

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

}

最佳答案

虽然接受的答案有其原因,但我相信解决方案也是必要的。

Spring 有一个 BufferingClientHttpRequestFactory,它充当 Rest Template 的默认 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/

关于Spring-boot Resttemplate response.body 为 null 而拦截器清楚地显示 body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49062866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com