httpclient 示例
时间: 2024-08-12 07:08:48 浏览: 35
HttpClient是一个常用的HTTP客户端库,它使得在编程中发送HTTP请求和处理响应变得更加方便。以下是一个使用Java的Apache HttpClient库发送GET请求的基本示例:
```java
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
// 创建HttpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 创建HttpGet对象,指定要访问的URL
HttpGet httpGet = new HttpGet("https://www.example.com");
// 发送GET请求
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
// 获取响应状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Status Code: " + statusCode);
// 获取响应体
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("Response Body: " + EntityUtils.toString(entity));
} else {
System.out.println("No content received.");
}
} finally {
// 关闭响应
response.close();
}
} finally {
// 关闭HttpClient连接
httpClient.close();
}
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.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)