apache httpClient Post案例
时间: 2024-01-30 08:37:00 浏览: 68
httpclient.post例子
5星 · 资源好评率100%
以下是一个基本的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;
import java.io.IOException;
public class HttpClientPostExample {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost("http://localhost:8080/api/post-example");
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 设置请求体
String json = "{\"name\": \"John\", \"age\": 30}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
// 发送请求
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
try {
// 获取响应体
HttpEntity httpEntity = httpResponse.getEntity();
String responseJson = EntityUtils.toString(httpEntity);
System.out.println(responseJson);
} finally {
httpResponse.close();
}
} finally {
httpClient.close();
}
}
}
```
在这个例子中,我们首先创建了一个HttpClient对象。然后,我们创建了一个HttpPost对象,并设置了请求头和请求体。最后,我们发送请求并获取响应体。
请注意,我们在try-with-resources块中使用了CloseableHttpResponse和CloseableHttpClient,以确保它们在使用后被关闭。此外,我们还使用了Apache HttpClient的EntityUtils类来处理响应体。
阅读全文