httpclient发送post请求
时间: 2023-09-27 22:10:15 浏览: 162
使用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.ContentType;
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 HttpClientExample {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api/post");
// 设置请求体
String requestBody = "{\"name\": \"John\", \"age\": 30}";
StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 发送请求
CloseableHttpResponse response = httpClient.execute(httpPost);
// 处理响应
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
String responseBody = EntityUtils.toString(responseEntity);
System.out.println(responseBody);
}
response.close();
httpClient.close();
}
}
```
在这个示例中,我们创建了一个默认的CloseableHttpClient实例,并设置POST请求的URL为http://example.com/api/post。我们使用StringEntity类来设置请求体,这个请求体是一个JSON字符串。最后,我们执行POST请求并处理响应。
阅读全文