httpclient断开连接
时间: 2023-09-27 21:05:31 浏览: 128
HttpClient断开连接可以通过以下步骤实现:
1. 创建一个HttpClient对象。
2. 创建一个HttpGet或HttpPost请求对象。
3. 调用execute方法发送请求并获取HttpResponse对象。
4. 从HttpResponse对象中获取响应内容。
5. 关闭HttpResponse对象和HttpClient对象。
下面是一个示例代码:
```java
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
try {
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpGet请求对象
HttpGet httpGet = new HttpGet("http://www.example.com");
// 发送请求并获取响应
HttpResponse response = httpClient.execute(httpGet);
// 获取响应内容
String responseBody = EntityUtils.toString(response.getEntity());
// 打印响应内容
System.out.println(responseBody);
// 关闭HttpResponse和HttpClient
response.close();
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文