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

Apache HttpClient 4.5.13如何构造含非字符串值的POST请求体?

Apache HttpClient 4.5.13构造多数据类型JSON请求体的解决方案

你之前的写法核心问题是混用了表单编码实体和JSON请求格式:UrlEncodedFormEntity是用于application/x-www-form-urlencoded类型的表单请求,而你设置了Content-Type: application/json;同时NameValuePair只能存储字符串值,无法保留整数、布尔等原始数据类型,导致API收到的JSON值全为字符串类型,不符合要求。

要构造正确的多数据类型JSON请求体,有两种可靠的方式:


方法1:手动构造JSON字符串,使用StringEntity

直接编写符合要求的JSON字符串,通过StringEntity设置到请求中,无需额外依赖:

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public static void main(String[] args) throws Exception {
    // 手动构造JSON字符串,保留原始数据类型
    String jsonBody = "{\n" +
            "  \"id\": 3,\n" +
            "  \"name\": \"Test\",\n" +
            "  \"accepted\": false,\n" +
            "  \"street\": \"foo bar ave.\"\n" +
            "}";

    HttpPost httpPost = new HttpPost("http://my-url.com/test-api");
    // 设置JSON实体并指定UTF-8编码
    StringEntity entity = new StringEntity(jsonBody, "UTF-8");
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    httpPost.setHeader("Accept", "application/json");

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(httpPost);

    // 后续响应处理逻辑...
}

方法2:使用JSON序列化库(如Jackson)自动生成JSON

如果请求结构复杂,手动编写JSON易出错,推荐用Jackson将Java对象序列化为JSON,自动保留数据类型:

步骤1:添加Jackson依赖(Maven示例)

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- 可按需选择适配版本 -->
</dependency>

步骤2:编写请求对应的Java实体类

public class RequestBody {
    private Integer id;
    private String name;
    private Boolean accepted;
    private String street;

    // 构造方法
    public RequestBody(Integer id, String name, Boolean accepted, String street) {
        this.id = id;
        this.name = name;
        this.accepted = accepted;
        this.street = street;
    }

    // 需添加getter/setter方法(或使用Lombok简化代码)
}

步骤3:用Jackson序列化对象并构造请求

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public static void main(String[] args) throws Exception {
    // 创建请求对象,设置对应类型的字段值
    RequestBody requestBody = new RequestBody(3, "Test", false, "foo bar ave.");

    // 用Jackson将对象序列化为JSON字符串
    ObjectMapper objectMapper = new ObjectMapper();
    String jsonBody = objectMapper.writeValueAsString(requestBody);

    HttpPost httpPost = new HttpPost("http://my-url.com/test-api");
    StringEntity entity = new StringEntity(jsonBody, "UTF-8");
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    httpPost.setHeader("Accept", "application/json");

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(httpPost);

    // 后续响应处理逻辑...
}

这两种方式都能确保请求体中的数据类型符合API要求,避免因字符串类型不匹配导致的请求失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:21:29