httpclient post setrequestbody 和setrequestentity 区别

RequestBody与RequestEntity对比
本文对比了HttpClient中RequestBody和RequestEntity的区别及使用场景。详细介绍了如何利用这两种方式发送POST请求,并指出在某些特定情况下,使用RequestBody能更好地完成任务。


setrequestbody
只对整个body




setrequestentity
可以是分段的内容

在处理自动提交表单的业务中往往要用到httpclient的poseMethod提交数据,httpclient3.1采用RequestEntity接口替代以前的RequestBody。
RequestEntity :

HttpClient client = new HttpClient();
PostMethod post = new PostMethod(redirectUrl);
		Part[] parts = {
				new StringPart("user", “aaa”),
				new StringPart("password", "bbb")
				};
		post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
client.executeMethod(post);
String result = post.getResponseBodyAsString();

RequestBody:
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(redirectUrl);
		NameValuePair[] pairs = {
			new NameValuePair("user", “aaa”),
                        new NameValuePair("password", “bbb”)
                        };
		post.setRequestBody(pairs);
client.executeMethod(post);
String result = post.getResponseBodyAsString();


在某些网站用RequestEntity方式请求有会失败,改成RequestBody就可以,可能就是这个原因。



<think>我们正在使用Spring BootApache HttpClient来发送一个带有自定义Header的POST请求,并且请求体是JSON格式。 根据引用[2]中的示例,我们可以设置Header信息为: httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); 同时,我们需要将JSON数据放入请求体中。 步骤: 1. 创建HttpClient实例。 2. 创建HttpPost对象,并设置目标URL。 3. 设置自定义Header,包括Content-TypeAccept等。 4. 构建JSON字符串,并设置到请求体中。 5. 执行请求并处理响应。 另外,我们可以使用Spring Boot的RestTemplate或者WebClient,但这里要求使用HttpClient。 考虑到代码的清晰性可维护性,我们可以使用HttpClient的CloseableHttpClient。 以下是一个示例代码:</think>在 Spring Boot 中使用 HttpClient 发送带自定义 Header 的 JSON POST 请求,可通过以下步骤实现: ### 实现步骤 1. **添加依赖** 在 `pom.xml` 中添加 Apache HttpClient 依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` 2. **创建 HttpClient 实例** ```java CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 3. **构建 POST 请求** ```java HttpPost httpPost = new HttpPost("https://api.example.com/endpoint"); // 设置自定义 Header httpPost.setHeader("Authorization", "Bearer your_token"); httpPost.setHeader("X-Custom-Header", "custom_value"); httpPost.setHeader("Content-type", "application/json"); // 必须声明 JSON 类型 httpPost.setHeader("Accept", "application/json"); // 构建 JSON 请求体 String jsonBody = "{\"name\":\"John\", \"age\":30}"; httpPost.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8)); ``` 4. **发送请求并处理响应** ```java try (CloseableHttpResponse response = httpClient.execute(httpPost)) { // 解析响应 String responseBody = EntityUtils.toString(response.getEntity()); int statusCode = response.getStatusLine().getStatusCode(); System.out.println("Status Code: " + statusCode); System.out.println("Response: " + responseBody); } finally { httpClient.close(); } ``` ### 关键点说明 1. **Header 设置** 必须包含 `Content-type: application/json` 声明请求体格式,自定义 Header 如 `X-Custom-Header` 按需添加。 2. **JSON 请求体** 使用 `StringEntity` 封装 JSON 字符串,并指定编码为 `UTF_8` 避免乱码。 3. **异常处理** 建议添加 `try-catch` 处理 `IOException` 连接超时等异常。 ### 完整示例 ```java import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.nio.charset.StandardCharsets; public class HttpClientJsonPost { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://api.example.com/data"); // 设置自定义 Header httpPost.setHeader("Authorization", "Bearer xyz123"); httpPost.setHeader("X-Request-ID", "req_789"); httpPost.setHeader("Content-type", "application/json"); // JSON 请求体 String json = "{\"product\":\"laptop\",\"price\":1200}"; httpPost.setEntity(new StringEntity(json, StandardCharsets.UTF_8)); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { System.out.println("Status: " + response.getStatusLine()); System.out.println("Body: " + EntityUtils.toString(response.getEntity())); } } } ``` ### 常见问题解决 - **中文乱码**:确保 `StringEntity` 使用 `StandardCharsets.UTF_8`。 - **SSL 证书**:需配置 `SSLContext` 处理 HTTPS(引用[3])。 - **连接池优化**:复用 `HttpClient` 实例提升性能(引用[1])。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半山猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值