使用 Spring RestTemplate 时调试 HTTP 请求和响应可能具有挑战性,因为它缺乏详细的日志记录信息。与curl的详细模式类似,您可能需要深入了解发送和接收的数据,包括标头和cookie。
您可以使用自定义的ClientHttpRequestInterceptor来代替修改RestTemplate源代码拦截并记录请求和响应数据。这是一个完整的示例:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor { final static Logger log = LoggerFactory.getLogger(LoggingRequestInterceptor.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================================================="); } }
要使用此拦截器,请使用 BufferingClientHttpRequestFactory 实例化 RestTemplate 并注册 LoggingRequestInterceptor:
RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(new LoggingRequestInterceptor()); restTemplate.setInterceptors(interceptors);
此解决方案提供了一种可自定义且方便的方法来捕获和记录记录请求和响应详细信息,帮助使用 Spring 进行故障排除和调试 RESTful Web 服务通信休息模板。
以上是如何使用 Spring RestTemplate 为请求和响应启用详尽的调试日志记录?的详细内容。更多信息请关注PHP中文网其他相关文章!