SpringBootRestTemplate打印http请求响应
前⾔
SpringBoot 的 RestTemplate是⼀个⽐较⽅便的http请求框架,在调试的时候我们需要查看http的request和response信息RestTemplate不会主动帮我们打印出来,但是我们可以在RestTemplate的中新增⼀个我们的log即可打印Http的必要信息。
代码实现如下:
springboot架构图private static final Logger logger = Logger(WebMvcConfigure.class);
private ClientHttpRequestInterceptor logClientHttpRequestInterceptor() {
return ((httpRequest, bytes, clientHttpRequestExecution) -> {
ClientHttpResponse response = ute(httpRequest, bytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
if (StatusCode() == HttpStatus.OK) {
byte[] bys = new byte[512];
int length;
while ((length = Body().read(bys)) > 0) {
outputStream.write(bys, 0, length);
}
}
if(logger.isDebugEnabled()) {
String reqMsg = "------------------------rest request----------------------------" +
"\r\n" +
"request url:" + URI() +
"\r\n" +
"request header:" + Headers().toString() +
"\r\n" +
"request method:" + MethodValue() +
"\r\n" +
"request body:" + new String(bytes) +
"\r\n" +
"------------------------------------------------------------------------" +
"\r\n" +
"\r\n" +
"--------------------------------rest response---------------------------" +
"\r\n" +
"response code:" + StatusCode() +
"\r\n" +
"response code msg:" + StatusText() +
"\r\n" +
"response headers:" + Headers().toString() +
"\r\n" +
"response body:" + new ByteArray(), StandardCharsets.UTF_8) +
"\r\n" + "---------------------------------------------------------------";
logger.debug(reqMsg);
}
return new ClientHttpResponseWrapper(response, ByteArray());
});
}
class ClientHttpResponseWrapper implements ClientHttpResponse {
private ClientHttpResponse response;
private InputStream in;
public ClientHttpResponseWrapper(ClientHttpResponse response, byte[] body) {
in = new ByteArrayInputStream(body);
}
}
@Override
public HttpStatus getStatusCode() throws IOException {            StatusCode();
}
@Override
public int getRawStatusCode() throws IOException {
RawStatusCode();
}
@Override
public String getStatusText() throws IOException {
StatusText();
}
@Override
public void close() {
try {
in.close();
response.close();
} catch (IOException e) {
}
}
@Override
public InputStream getBody() throws IOException {
return in;
}
@Override
public HttpHeaders getHeaders() {
Headers();
}
}
效果图:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。