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

Java发送带JSON body的POST请求返回400错误如何解决

问题根因分析

  • 输出流未主动刷新关闭:请求体写入OutputStream后没有调用flush()或close(),部分场景下会导致请求体未完整发送到服务端
  • 错误响应读取逻辑缺失:HTTP 400属于客户端错误响应,此时直接调用getInputStream()会直接抛出IO异常,无法读取服务端返回的具体错误提示,无法定位根因
  • 响应读取逻辑错误:使用in.ready()判断是否结束读取是错误用法,该方法仅判断当前流是否有可读取的字节,不等同于流已传输完成,会出现响应读取不全的问题
  • Content-Type属性缺失字符集声明:部分服务端会严格校验请求头的字符集,未声明utf-8可能导致请求体解析失败

修复后的代码

public class PostRequest {

    public void sendPost(String Url) throws IOException {
        FileWriter myWriter = null;
        String name = "{\"messageName\": \"URLFound\", \"businessKey\": \"3\"}";
        
        try {
            myWriter = new FileWriter("C:\\Users\\test\\Desktop\\camunda test save\\Post.txt");
            // 这里建议先校验Url参数是否以/开头,避免拼接错误
            URL url = new URL("http://localhost:8080/engine-rest" + Url);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            
            http.setRequestMethod("POST");
            http.setDoOutput(true);
            // 补充charset声明
            http.setRequestProperty("Content-Type", "application/json; utf-8");
            // 可选添加Accept头,声明接收JSON响应
            http.setRequestProperty("Accept", "application/json");
            
            // try-with-resources自动关闭输出流,自动flush
            try (OutputStream os = http.getOutputStream()) {
                byte[] input = name.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
            
            // 先获取响应码,区分正常响应和错误响应
            int responseCode = http.getResponseCode();
            StringBuilder response = new StringBuilder();
            // 错误响应读ErrorStream
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(responseCode < 400 ? http.getInputStream() : http.getErrorStream()))) {
                String line;
                // 正确的流结束判断逻辑
                while ((line = in.readLine()) != null) {
                    response.append(line);
                }
            }
            
            // 写入结果,把响应码也写上方便排查
            myWriter.append("响应码:").append(String.valueOf(responseCode))
                    .append("\n响应内容:").append(response.toString())
                    .append("\n请求URL:").append(url.toString());

        } catch (Exception e) {
            if (myWriter != null) {
                myWriter.append("请求异常:").append(e.toString());
            }
            e.printStackTrace();
        } finally {
            if (myWriter != null) {
                myWriter.close();
            }
        }
    }
}

额外排查建议

修复后运行代码,查看Post.txt中记录的服务端错误响应内容,即可明确是请求体字段错误、参数缺失还是鉴权等其他问题导致的400报错。

内容的提问来源于stack exchange,提问作者Hadi Hoteit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:39:04