通过restTemplate
发送的http请求会被拦截,方便开发调试,正式环境尽量别用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| 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;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets;
public class HttpInterceptor implements ClientHttpRequestInterceptor {
private final Logger log = LoggerFactory.getLogger(HttpInterceptor.class);
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { logRequest(request, body); ClientHttpResponse response = execution.execute(request, body);
return response; }
private void logRequest(HttpRequest request, byte[] body) { log.info("Request URI: " + request.getURI()); log.info("Method: " + request.getMethod()); log.info("Headers: " + request.getHeaders()); if (body.length > 0) { String requestBody = new String(body, StandardCharsets.UTF_8); log.info("Request Body: " + requestBody); } }
private void logResponse(ClientHttpResponse response) throws IOException { log.info("Response Status Code: " + response.getStatusCode()); log.info("Response Headers: " + response.getHeaders());
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(); } log.info("Response Body: " + inputStringBuilder.toString()); } }
|