使用HttpClients
时间: 2023-11-24 16:07:50 浏览: 38
HttpClients 是 Apache HttpComponents 的一个 Java 库,它提供了一个简单易用的 API 来发送 HTTP 请求和接收 HTTP 响应。下面是一些使用 HttpClients 的示例:
1. 发送 GET 请求:
```java
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.example.com");
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
// 处理响应内容
} finally {
response.close();
}
```
2. 发送 POST 请求:
```java
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.example.com");
StringEntity entity = new StringEntity("request body", ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
HttpEntity responseEntity = response.getEntity();
// 处理响应内容
} finally {
response.close();
}
```
3. 发送带参数的 GET 请求:
```java
CloseableHttpClient httpclient = HttpClients.createDefault();
URIBuilder builder = new URIBuilder("http://www.example.com");
builder.setParameter("param1", "value1")
.setParameter("param2", "value2");
HttpGet httpGet = new HttpGet(builder.build());
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
// 处理响应内容
} finally {
response.close();
}
```
以上是 HttpClients 的一些基本用法示例,你可以根据具体需求进行更多的定制。需要注意的是,HttpClients 会创建一个连接池来管理连接,因此在使用完毕后需要手动关闭连接,以便释放资源。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)