httpclient怎么用get
时间: 2023-10-01 16:05:02 浏览: 106
使用 HttpClient 进行 GET 请求的基本步骤如下:
1. 创建一个 HttpClient 对象:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
```
2. 创建一个 HttpGet 对象,并设置请求的 URL:
```java
HttpGet httpGet = new HttpGet("http://example.com/api/endpoint");
```
3. 发送 GET 请求并获取响应:
```java
CloseableHttpResponse response = httpClient.execute(httpGet);
```
4. 处理响应结果:
```java
try {
// 获取响应状态码
int statusCode = response.getStatusLine().getStatusCode();
// 读取响应内容
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
// 处理响应结果
if (statusCode == HttpStatus.SC_OK) {
System.out.println("请求成功");
System.out.println("响应内容:" + responseBody);
} else {
System.out.println("请求失败,状态码:" + statusCode);
}
} finally {
// 关闭响应对象和 HttpClient
response.close();
httpClient.close();
}
```
以上代码示例使用了 HttpClient 4.x 版本的 API。请确保已添加相应的依赖库。
阅读全文