httpclient 示例
时间: 2024-08-12 14:08:48 浏览: 58
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();
}
}
}
```
阅读全文