RestTemplate一般用于方法内部请求调用,请求报错时难以调试,所以可以为RestTemplate加拦截器进行调试,具体操作如下:
拦截器LoggingClientHttpRequestInterceptor:
package cn.ucmed.otaka.healthcare.interceptor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; @Slf4j public class LoggingClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { tranceRequest(request, body); ClientHttpResponse response = execution.execute(request, body); traceResponse(response); return response; } private void tranceRequest(HttpRequest request, byte[] body) throws UnsupportedEncodingException { log.info("======= request begin ========"); log.info("uri : {}", request.getURI()); log.info("method : {}", request.getMethod()); log.info("headers : {}", request.getHeaders()); log.info("request body : {}", new String(body, "UTF-8")); log.info("======= request end ========"); } private void traceResponse(ClientHttpResponse response) throws IOException { StringBuilder inputStringBuilder = new StringBuilder(); try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"))) { String line = bufferedReader.readLine(); while (line != null) { inputStringBuilder.append(line); inputStringBuilder.append(' '); line = bufferedReader.readLine(); } } log.info("============================response begin=========================================="); log.info("Status code : {}", response.getStatusCode()); log.info("Status text : {}", response.getStatusText()); log.info("Headers : {}", response.getHeaders()); log.info("Response body: {}", inputStringBuilder.toString()); log.info("=======================response end================================================="); } }
在启动类里面对RestTemplate实例添加拦截器
@Bean public RestTemplate getRestTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.getInterceptors().add(new LoggingClientHttpRequestInterceptor()); return restTemplate; }
效果如下: