httpclient发送POST请求 java代码
时间: 2024-10-23 09:20:02 浏览: 34
在Java中,可以使用Apache HttpClient库来发送POST请求。以下是一个简单的示例,展示了如何创建一个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 HttpPostExample {
private static final String URL = "http://example.com/api/endpoint";
public void sendPostRequest() {
CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpClient实例
try {
// 创建HttpPost对象,指定请求地址
HttpPost httpPost = new HttpPost(URL);
// 设置POST数据,这里是一个简单的String,如果是复杂数据可以用JsonEntity
String requestBody = "{\"key\":\"value\"}";
httpPost.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
// 发送请求
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
// 检查状态码
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
// 从响应中获取实体并处理数据
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
System.out.println("Received response: " + responseBody);
} else {
throw new RuntimeException("Failed to execute request: " + response.getStatusLine());
}
} finally {
// 关闭响应和客户端资源
response.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close(); // 关闭HttpClient
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
在这个例子中,我们首先创建了一个`CloseableHttpClient`实例,然后创建一个`HttpPost`对象,设置请求头和POST数据。接着,我们执行请求并检查响应的状态码,最后关闭响应和客户端资源。
阅读全文