httpclient post json 格式传参

本文介绍了一个具体的API调用示例,用于获取直播平台的用户统计数据,包括设置请求头、构建请求体及处理响应等关键步骤。
/**
* 获取用户统计数据(目睹的数据统计)

* @author fuyongjin 2018-1-17
* @param url
* @param filter
*            1 表示查看观看直播时间长于1分钟的用户,0 表示所有
* @param headreq
* @param pageNum
*            页面 默认1 (默认每页数据20条)
* @return
*/
public static HttpStrBean doPost(String url, JsonObject requestBody, Map<String, String> headreq) {
HttpStrBean bean = new HttpStrBean();
bean.setSuccess(false);
if (StringUtil.isEmpty(url)) {
bean.setMsg("url链接为空");
return bean;
}


org.apache.http.client.HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url); // post方法
try {
// 遍历便捷请求头
for (Map.Entry<String, String> entry : headreq.entrySet()) {
method.setHeader(entry.getKey(), entry.getValue());


}
StringEntity entity = new StringEntity(requestBody.toString(),
Charset.forName("UTF-8"));
method.setEntity(entity);
HttpResponse result = client.execute(method); // 执行请求


/** 请求发送成功,并得到响应 **/
if (result.getStatusLine().getStatusCode() == 200) {

/** 读取服务器返回过来的json字符串数据 **/
String str = EntityUtils.toString(result.getEntity());
bean.setResult(str); // 以字符串的形式返回结果
bean.setMsg("200");
bean.setSuccess(true);
return bean;

} else {
bean.setMsg("200 errcode: "
+ result.getStatusLine().getStatusCode());
return bean;
}
} catch (URIException e) {
// log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
bean.setMsg(e.getMessage());
} catch (IOException e) {
// log.error("执行HTTP Get请求" + url + "时,发生异常!", e);
bean.setMsg(e.getMessage());
} finally {
method.releaseConnection();
}
return bean;
}


public static void main(String[] args) {
// String url = "http://api.mudu.tv/v1/activities";
String url = "http://api.mudu.tv/v1/activities/95392/visitors";
Map<String, String> headreq = new HashMap<String, String>();
headreq.put("Authorization", "Bearer 4kzmkwxtbaw2ja95gq5d629wxvwcmsej");
headreq.put("Content-Type", "application/json");


JsonObject json = new JsonObject();
json.addProperty("filter", 0);
json.addProperty("perPage", 5);
json.addProperty("p", 1);


HttpStrBean httpStrBean = doPost(url, json, headreq);
String result = httpStrBean.getResult();
List<VLiveUserCount> parseObject = JSONObject.parseArray(
httpStrBean.getResult(), VLiveUserCount.class);
System.out.println(parseObject.size());
System.out.println(result);


}
<think>我们正在讨论如何使用HttpPost的setEntity方法来传递JSON参数。根据提供的引用,有两种方法可以实现这一点: 方法1(来自引用[^1]): 这种方法将JSON字符串作为表单参数传递,使用`UrlEncodedFormEntity`。这通常用于模拟表单提交,但并不是直接传递JSON对象的方式。具体步骤如下: 1. 创建一个`List<NameValuePair>`,例如一个`ArrayList`。 2. 添加一个键值对,其中键是参数名(如"param"),值是JSON字符串。 3. 使用`UrlEncodedFormEntity`包装这个列表,并设置编码(如UTF-8)。 4. 将这个实体设置到HttpPost对象中。 但是,这种方法并不是直接传递JSON,而是将JSON作为表单的一个字段值传递。如果服务器期望接收的是application/json格式的数据,这种方法可能不适用。 方法2(来自引用[^2]): 这是一种更直接的方式,将JSON字符串作为请求体直接发送,并设置Content-Type为application/json。步骤如下: 1. 创建一个HttpPost对象,指定URL。 2. 设置请求头:Content-Type为application/json;charset=utf8。 3. 使用`StringEntity`来封装JSON字符串,并指定编码(如utf-8)。 4. 将这个实体设置到HttpPost对象中。 显然,方法2是更常见的传递JSON参数的方式,因为它符合RESTful API中传递JSON数据的标准做法。 因此,推荐使用第二种方法。以下是具体代码示例: ```java // 假设我们有一个JSON字符串 String json = "{\"key1\":\"value1\", \"key2\":\"value2\"}"; // 创建HttpPost对象 HttpPost httpPost = new HttpPost("http://example.com/api"); // 设置请求头,指定内容类型为JSON httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); // 创建请求实体,使用JSON字符串和编码 httpPost.setEntity(new StringEntity(json, StandardCharsets.UTF_8)); // 执行请求 try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost)) { // 处理响应... } ``` 注意:上述代码使用了Java 7的try-with-resources语句,确保资源被正确关闭。另外,需要导入相应的包。 **总结**:要使用HttpPost的setEntity传递JSON参数,应该创建一个`StringEntity`,内容为JSON字符串,并设置Content-Type请求头为`application/json`。这样服务器就能正确解析请求体中的JSON数据。 相关问题: 1. 如何在使用HttpClient发送POST请求时设置其他请求头(如认证头)? 2. 如何处理HttpClient发送JSON请求后返回的JSON响应? 3. 在使用HttpClient发送JSON数据时,如何处理可能出现的异常?</think>### 使用 HttpPost setEntity 传递 JSON 参数 通过 `setEntity` 传递 JSON 参数的核心步骤是创建包含 JSON 数据的实体对象,并设置正确的 Content-Type 请求头。以下是两种推荐方法: #### ✅ 方法 1:直接使用 StringEntity(推荐) ```java // 创建 JSON 字符串 String json = "{\"name\":\"张三\",\"age\":25}"; HttpPost httpPost = new HttpPost("https://api.example.com/data"); // 关键步骤:设置 JSON 内容类型 httpPost.setHeader("Content-Type", "application/json; charset=UTF-8"); // 关键步骤:创建 JSON 实体 httpPost.setEntity(new StringEntity(json, StandardCharsets.UTF_8)); // 发送请求 try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost)) { // 处理响应... } ``` **关键点:** - 必须设置 `Content-Type: application/json` 请求头 - 使用 `StringEntity` 直接包装 JSON 字符串 - 显式指定 UTF-8 编码防止乱码 #### ⚠️ 方法 2:表单方式(不推荐,仅兼容旧系统) ```java List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("json_data", json)); // JSON 作为表单字段值 HttpPost httpPost = new HttpPost("https://api.example.com/data"); // 注意:这里使用表单的 Content-Type httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); ``` 此方法将 JSON 作为表单字段传递,需服务器特殊处理[^1],**现代 API 不建议使用**。 #### 📌 最佳实践 1. **编码处理** 使用 `StandardCharsets.UTF_8` 或 `"UTF-8"` 明确指定编码 2. **异常处理** 添加 try-catch 处理 `IOException` 3. **资源释放** 使用 try-with-resources 自动关闭连接 4. **依赖库** 确保引入 Apache HttpClient 库: ```xml <!-- Maven 依赖 --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` > ⚠️ **常见错误**:未设置 `Content-Type` 会导致服务器无法识别 JSON 数据,返回 400 错误[^2]。 ### 相关问题 1. 如何用 HttpClient 处理 POST 请求返回的 JSON 响应? 2. 在 Android 开发中发送 JSON 数据与 Java 有何不同? 3. HttpClient 和 OkHttp 在 JSON 处理上有什么性能差异? 4. 如何为 JSON 请求添加认证头(如 Bearer Token)? [^1]: 表单方式传递 JSON 需要服务器解析表单后再提取 JSON 字符串 [^2]: 缺少 `Content-Type: application/json` 是 JSON 请求失败的常见原因
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值