我正在使用 RestTemplate
和 Spring 执行 HTTP GET 请求。
如何在每个请求时自动记录日志文件中的请求和响应数据?
我正在使用 RestTemplate
和 Spring 执行 HTTP GET 请求。
如何在每个请求时自动记录日志文件中的请求和响应数据?
@Component
public class LogRequestResponseFilter implements ClientHttpRequestInterceptor {
private static final Logger logger=LoggerFactory.getLogger(LogRequestResponseFilter.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
traceRequest(request, body);
ClientHttpResponse clientHttpResponse = execution.execute(request, body);
traceResponse(clientHttpResponse);
return clientHttpResponse;
}
private void traceRequest(HttpRequest request, byte[] body) throws IOException {
logger.debug("request URI : " + request.getURI());
logger.debug("request method : " + request.getMethod());
logger.debug("request body : " + getRequestBody(body));
}
private String getRequestBody(byte[] body) throws UnsupportedEncodingException {
if (body != null && body.length > 0) {
return (new String(body, "UTF-8"));
} else {
return null;
}
}
private void traceResponse(ClientHttpResponse response) throws IOException {
String body = getBodyString(response);
logger.debug("response status code: " + response.getStatusCode());
logger.debug("response status text: " + response.getStatusText());
logger.debug("response body : " + body);
}
private String getBodyString(ClientHttpResponse response) {
try {
if (response != null && response.getBody() != null) {// &&
// isReadableResponse(response))
// {
StringBuilder inputStringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), StandardCharsets.UTF_8));
String line = bufferedReader.readLine();
while (line != null) {
inputStringBuilder.append(line);
inputStringBuilder.append('\n');
line = bufferedReader.readLine();
}
return inputStringBuilder.toString();
} else {
return null;
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
return null;
}
}
@Component
到自定义的Interceptor
是否足够?还是我必须在某个地方显式注册它,例如在RestTemplate
上?因为这就是我想要避免的:不得不自己注册和连接。 - membersoundInputStream
不支持标记怎么办?一旦读取完成就会消失。 - Captain Man
org.springframework.http.client.InterceptingClientHttpRequest
和org.springframework.http.client.SimpleClientHttpResponse
的 Java 对象。我需要的是响应的文本/XML表示形式,并将其记录下来。 - membersound