httpclient post 示例
时间: 2024-11-24 07:20:23 浏览: 7
HttpClient是一个在Java中用于HTTP客户端操作的库,常用于发送HTTP请求,包括POST方法。下面是一个简单的示例,展示如何使用Apache HttpClient库进行POST请求:
```java
import org.apache.http.HttpEntity;
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;
import org.apache.http.util.EntityUtils;
public class HttpClientPostExample {
public static void main(String[] args) throws Exception {
// 创建HttpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 创建HttpPost对象并设置URL
HttpPost httpPost = new HttpPost("http://example.com/api/endpoint");
// 设置POST数据
String jsonContent = "{\"key\":\"value\"}";
StringEntity inputEntity = new StringEntity(jsonContent);
httpPost.setEntity(inputEntity);
// 发送请求
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
// 获取响应状态码
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code : " + responseCode);
// 如果成功,获取响应体作为字符串
if (responseCode == 200) {
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
System.out.println("Response Body : " + responseBody);
} else {
System.err.println("Error posting data. Status code: " + responseCode);
}
} finally {
// 关闭连接
response.close();
}
} finally {
// 最后关闭HttpClient
httpClient.close();
}
}
}
```
在这个例子中,我们创建了一个`HttpPost`对象,并设置了目标URL以及POST的数据(这里是一个JSON字符串)。然后通过`HttpClient`执行请求,并处理响应结果。
阅读全文