调试 Java 中的 HTTP 请求,通常可以从代码层、网络层、工具层三个角度入手。下面按常见场景给你一个实用指南。
无论用哪种 HTTP 客户端,第一步都是“看清楚发了什么、回了什么”。
HttpClient 示例HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/api"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"test\"}"))
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println("Headers: " + response.headers());
System.out.println("Body: " + response.body());
✅ 重点打印:
Content-Type、Authorization)如果你用的是 Apache HttpClient / OkHttp / Spring RestTemplate / WebClient,可以开启 HTTP 日志。
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
日志会显示:
restTemplate.getInterceptors().add(
new LoggingClientHttpRequestInterceptor()
);
WebClient.builder()
.filter(ExchangeFilterFunction.ofRequestProcessor(
req -> {
System.out.println(req.method() + " " + req.url());
return Mono.just(req);
}
))
.build();
curl 对比测试curl -X POST https://example.com/api \
-H "Content-Type: application/json" \
-d '{"name":"test"}'
如果 curl 成功但 Java 失败:
-Dhttps.proxyHost=127.0.0.1
-Dhttps.proxyPort=8888
或代码中:
System.setProperty("https.proxyHost", "127.0.0.1");
System.setProperty("https.proxyPort", "8888");
✅ 可以清楚看到:
Content-Type 不对Authorization vs token)client.send(request, BodyHandlers.ofString());
可能原因:
-Djavax.net.debug=all
会打印 SSL / TCP 层细节(信息非常多)。
再写 Java 代码,避免“代码和接口一起错”。
如果你愿意,可以告诉我:
我可以直接帮你定位问题。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。