You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用RestTemplate发送POST请求遇400错误,如何查看请求JSON串?

如何查看RestTemplate发送的JSON请求体(解决400 Bad Request问题)

哎,遇到400 Bad Request确实挺闹心的,毕竟光看错误码根本不知道哪出问题了。要拿到实际发送的JSON其实有好几种实用办法,我给你整理一下:

方法一:手动序列化对象直接打印

你可以用Jackson的ObjectMapper把要发送的smsMessages对象直接转成JSON字符串,这样就能直观看到请求体内容。把这段代码加在构建HttpEntity之前就行:

// Spring项目一般自带Jackson依赖,直接用就行
ObjectMapper objectMapper = new ObjectMapper();
try {
    String requestJson = objectMapper.writeValueAsString(smsMessages);
    System.out.println("实际发送的JSON请求体:");
    System.out.println(requestJson);
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

方法二:给RestTemplate加请求拦截器

这种方法能实时拦截请求,不仅能看请求体,还能查看响应内容,调试起来更全面:

// 给RestTemplate添加自定义拦截器
restTemplate.getInterceptors().add((request, body, execution) -> {
    // 打印请求URL和请求体
    String requestBody = new String(body, StandardCharsets.UTF_8);
    System.out.println("请求URL:" + request.getURI());
    System.out.println("请求体:" + requestBody);
    
    // 执行请求并打印响应信息
    ClientHttpResponse response = execution.execute(request, body);
    String responseBody = new String(StreamUtils.copyToByteArray(response.getBody()), StandardCharsets.UTF_8);
    System.out.println("响应状态码:" + response.getStatusCode());
    System.out.println("响应体:" + responseBody);
    
    return response;
});

注意要引入org.springframework.util.StreamUtils和java.nio.charset.StandardCharsets这两个类。

方法三:通过日志框架开启调试日志

如果你的项目用了Logback或Log4j,直接配置日志级别就能让RestTemplate自动打印完整请求细节。比如在logback.xml里添加这段配置:

<logger name="org.springframework.web.client.RestTemplate" level="DEBUG"/>

启动项目后,日志里就会输出请求头、请求体、响应状态码和响应内容,不用改代码就能调试。


拿到JSON字符串后,你就可以用curl命令模拟请求测试了,示例如下:

curl -X POST \
  -H "Content-Type: application/json" \
  -d '替换成你打印出来的JSON字符串' \
  你的POST_MESSAGE_URL地址

这样就能排查是不是JSON格式错误、参数缺失或不符合接口要求导致的400错误。

内容的提问来源于stack exchange,提问作者Nunyet Calçada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:55:46