HttpClient结合PostMethod调用接口

本文介绍如何使用HttpClient和PostMethod进行接口调用的方法,包括设置请求头、请求参数,执行请求并获取响应状态码及结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HttpClient结合PostMethod调用接口

 
 

 

 

解决方法:

HttpClient client = new HttpClient();

PostMethod post = new PostMethod("http://192.168.0.189:8500/short");

post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");// 在头文件中设置转码

post.setRequestHeader("Connection", "close");

NameValuePair[] data = { new NameValuePair("username", this.username), new NameValuePair("passwd", this.passwd))};

post.setRequestBody(data);

client.executeMethod(post);

Header[] headers = post.getResponseHeaders();

int statusCode = post.getStatusCode();

String result = new String(post.getResponseBodyAsString().getBytes());

转载于:https://www.cnblogs.com/chinaifae/p/10188862.html

<think>我们正在使用HttpClientPostMethod来发送POST请求,并且需要正确设置Content-Type。根据引用[1]中的经验,即使设置了Content-Type为json,但实际发送时可能仍然是application/x-www-form-urlencoded,导致服务器返回400错误。引用[2]提到了乱码问题,但这里我们主要关注Content-Type的设置。 HttpClient 3.x中,PostMethod设置Content-Type的注意事项: 1. 使用`setRequestHeader`方法设置Content-Type可能会被覆盖,特别是当调用`setRequestBody`方法时,因为HttpClient会根据请求体的类型自动设置Content-Type。如果我们希望使用自定义的Content-Type(如application/json),则需要避免使用`setRequestBody`方法设置参数,而是使用`setRequestEntity`方法,并同时设置Content-Type。 2. 对于发送JSON数据,我们可以使用`StringRequestEntity`来设置请求体和Content-Type。 具体步骤: - 创建PostMethod实例。 - 创建StringRequestEntity,将JSON字符串作为请求体,并指定Content-Type为"application/json"和字符编码(如UTF-8)。 - 使用setRequestEntity方法设置请求实体。 这样,Content-Type就会被正确设置为application/json,而不会被覆盖。 示例代码: ```java import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; public class JsonPostExample { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; String jsonBody = "{\"key\":\"value\"}"; HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); // 创建请求实体,指定JSON字符串,Content-Type和编码 StringRequestEntity requestEntity = new StringRequestEntity( jsonBody, "application/json", "UTF-8"); post.setRequestEntity(requestEntity); // 执行请求 int statusCode = client.executeMethod(post); System.out.println("Status Code: " + statusCode); System.out.println("Response: " + post.getResponseBodyAsString()); post.releaseConnection(); } } ``` 注意:如果使用`setRequestBody`方法,HttpClient可能会将Content-Type设置为默认的application/x-www-form-urlencoded,因此应避免在设置自定义Content-Type时使用该方法。 另外,引用[2]提到乱码问题,我们设置StringRequestEntity时指定了编码为UTF-8,这也有助于避免乱码。 总结: - 使用StringRequestEntity来设置请求体和Content-Type。 - 避免使用setRequestBody方法,因为它会覆盖Content-Type。 如果使用HttpClient 4.x,方法会有所不同,但用户的问题中引用的是commons-httpclient-3.1,所以以上代码适用于3.1版本。 §§相关问题§§ 1. 如何在HttpClient 4.x中设置Content-Type? 2. 如何解决HttpClient发送JSON数据时的乱码问题? 3. 除了JSON,HttpClient如何发送XML格式的数据?</think>### HttpClient PostMethod 正确设置 Content-Type 指南 在使用 Apache HttpClient 的 `PostMethod` 时,正确设置 Content-Type 至关重要。根据引用[1]的经验,即使设置了 Content-Type,仍可能被默认值覆盖导致 400 错误。以下是解决方案: #### 核心问题分析 - 直接调用 `setRequestBody()` 会强制覆盖为 `application/x-www-form-urlencoded`[^1] - 字符集编码问题可能导致乱码(引用[2]) - 需要同时处理内容类型和字符集设置 #### 正确设置方法(HttpClient 3.x) ```java import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.*; // 创建POST请求 PostMethod post = new PostMethod("http://example.com/api"); post.setRequestHeader("Content-Type", "application/json; charset=utf-8"); // 正确设置请求体(避免使用setRequestBody) String jsonBody = "{\"name\":\"测试数据\"}"; post.setRequestEntity(new StringRequestEntity( jsonBody, "application/json", // MIME类型 "UTF-8" // 字符集 )); // 执行请求 HttpClient client = new HttpClient(); int status = client.executeMethod(post); System.out.println("响应状态: " + status); ``` #### 关键步骤说明 1. **使用 StringRequestEntity** - 避免直接使用 `setRequestBody()` - 同时指定内容类型和字符集 - 支持任何文本格式:JSON/XML/Text 等 2. **二进制文件上传** ```java File audioFile = new File("audio.mp3"); post.setRequestEntity(new FileRequestEntity( audioFile, "audio/mpeg" // 根据文件类型设置 )); ``` 3. **解决乱码问题(引用[2])** - 始终显式指定字符集(如 UTF-8) - 重写 `getRequestCharSet()` 方法可自定义编码 #### 常见错误解决方案 | 错误现象 | 原因 | 解决方案 | |---------|------|---------| | 400 Bad Request | 默认使用 x-www-form-urlencoded | 改用 StringRequestEntity | | 响应乱码 | 字符集未指定 | 在 Content-Type 中添加 charset 参数 | | 文件上传失败 | 错误 MIME 类型 | 使用 `Files.probeContentType()` 检测真实类型 | #### 最佳实践建议 1. 对于 JSON 数据: ```java post.setRequestEntity(new StringRequestEntity( jsonData, "application/json", "UTF-8" )); ``` 2. 对于表单数据: ```java NameValuePair[] data = { new NameValuePair("user", "张三"), new NameValuePair("file", "audio.mp3") }; post.setRequestBody(data); // 此时允许使用默认类型 ``` > **重要提示**:当使用 `setRequestEntity()` 时,不要再调用 `setRequestBody()` 或 `setRequestHeader("Content-Type")`,否则会造成设置冲突[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值