java 如何打印报文
打印报文的方法
在Java中打印报文(通常指HTTP请求或响应的报文)可以通过多种方式实现,具体取决于使用的网络库或框架。以下是几种常见的方法:
使用HttpURLConnection打印请求和响应报文
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class PrintHttpMessage {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 打印请求头
System.out.println("Request Headers:");
connection.getRequestProperties().forEach((k, v) -> System.out.println(k + ": " + v));
// 发送请求
int responseCode = connection.getResponseCode();
// 打印响应头
System.out.println("\nResponse Headers:");
connection.getHeaderFields().forEach((k, v) -> System.out.println(k + ": " + v));
// 打印响应体
System.out.println("\nResponse Body:");
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
}
}
}
使用Apache HttpClient打印报文
如果使用Apache HttpClient库,可以更灵活地打印报文:
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class PrintHttpMessageWithHttpClient {
public static void main(String[] args) throws Exception {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet request = new HttpGet("http://example.com");
// 打印请求报文
System.out.println("Request Line: " + request.getRequestLine());
System.out.println("Request Headers:");
Arrays.stream(request.getAllHeaders()).forEach(System.out::println);
// 执行请求
HttpResponse response = httpClient.execute(request);
// 打印响应报文
System.out.println("\nResponse Status: " + response.getStatusLine());
System.out.println("Response Headers:");
Arrays.stream(response.getAllHeaders()).forEach(System.out::println);
System.out.println("\nResponse Body:");
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
}
使用Spring WebClient打印报文(Spring 5+)
在Spring WebFlux应用中,可以使用WebClient打印报文:
import org.springframework.web.reactive.function.client.WebClient;
public class PrintHttpMessageWithWebClient {
public static void main(String[] args) {
WebClient webClient = WebClient.create("http://example.com");
webClient.get()
.exchangeToMono(clientResponse -> {
// 打印响应头
System.out.println("Response Headers:");
clientResponse.headers().asHttpHeaders().forEach((name, values) ->
values.forEach(value -> System.out.println(name + ": " + value)));
// 返回响应体并打印
return clientResponse.bodyToMono(String.class);
})
.doOnNext(body -> System.out.println("\nResponse Body:\n" + body))
.block();
}
}
使用日志框架打印报文
在生产环境中,通常使用日志框架(如SLF4J+Logback)来记录报文:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogHttpMessages {
private static final Logger logger = LoggerFactory.getLogger(LogHttpMessages.class);
public void logRequest(String url, String headers, String body) {
logger.debug("HTTP Request:\nURL: {}\nHeaders:\n{}\nBody:\n{}", url, headers, body);
}
public void logResponse(int status, String headers, String body) {
logger.debug("HTTP Response:\nStatus: {}\nHeaders:\n{}\nBody:\n{}", status, headers, body);
}
}
注意事项
- 生产环境中打印完整报文可能包含敏感信息,需谨慎处理
- 对于大型报文,考虑截断或摘要打印以避免性能问题
- 使用日志框架时,可配置不同级别(DEBUG/INFO)来控制报文打印
以上方法覆盖了从基础Java网络API到流行框架的报文打印需求,可根据具体场景选择合适的方式。






