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

Unirest发送带JSON体的POST请求时出现空字段异常

问题解决:Unirest POST/PUT请求实体字段为空,Postman却正常

问题根源是未设置Content-Type请求头:

Postman发送JSON请求时会自动添加Content-Type: application/json头,明确告知服务器请求体为JSON格式,服务器能正确解析并映射到实体类。但你的Unirest代码仅设置了Accept头(用于指定接受JSON响应),没有声明请求体的类型,导致服务器无法识别你发送的JSON字符串,最终实体字段全部为空。

修改后的代码

只需添加Content-Type头即可解决:

String entityJson = gson.toJson(entity);
System.out.println(entityJson);

HttpResponse<JsonNode> response = Unirest.post("http://localhost:8080/post/")
        .header("Accept", "application/json")
        .header("Content-Type", "application/json") // 新增此行,指定请求体格式
        .body(entityJson)
        .asJson();
System.out.println(response.getBody().toPrettyString());

简化写法(可选)

如果不需要手动用Gson序列化,也可以直接将实体对象传给body方法,Unirest会自动完成JSON序列化并设置正确的Content-Type头:

HttpResponse<JsonNode> response = Unirest.post("http://localhost:8080/post/")
        .header("Accept", "application/json")
        .body(entity) // 直接传入实体对象
        .asJson();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:15:00