HttpClient是一个开源的Java HTTP客户端库,可以发送HTTP请求,并接收HTTP响应。
使用HttpClient发送GET请求的基本步骤如下:
1. 创建HttpClient对象:
```
CloseableHttpClient httpClient = HttpClients.createDefault();
```
2. 创建HttpGet对象,并设置请求的URL:
```
HttpGet httpGet = new HttpGet("http://www.example.com");
```
3. 执行GET请求并获取响应:
```
CloseableHttpResponse response = httpClient.execute(httpGet);
```
4. 解析响应:
- 获取响应状态码:
```
int statusCode = response.getStatusLine().getStatusCode();
```
- 获取响应内容:
```
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
```
5. 关闭HttpClient和HttpResponse:
```
response.close();
httpClient.close();
```
完整的示例代码如下:
```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;
import org.apache.http.util.EntityUtils;
public class HttpClientDemo {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.example.com");
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
System.out.println("Status Code: " + statusCode);
System.out.println("Response Content: " + responseContent);
} finally {
response.close();
}
httpClient.close();
}
}
```
以上代码发送一个GET请求到`http://www.example.com`,并输出响应状态码和响应内容。