CloseableHttpClient发送get带header
时间: 2024-09-19 13:01:48 浏览: 30
后台模拟发送GET和POST请求
CloseableHttpClient是Apache HttpClient库中的一个接口,用于创建可以关闭连接的HTTP客户端。如果你想要通过它发送GET请求并携带自定义Header,你可以按照以下步骤操作:
1. 首先,你需要创建一个`CloseableHttpResponse`对象,这通常会涉及到`HttpGet`和`HttpClient`的配合。
```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 CloseableHttpResponse sendGetWithHeaders(String url, Map<String, String> headers) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet request = new HttpGet(url);
// 添加headers到请求中
for (String key : headers.keySet()) {
request.setHeader(key, headers.get(key));
}
return httpClient.execute(request);
} catch (Exception e) {
throw new RuntimeException("Error sending GET request", e);
}
}
```
在这个例子中,`Map<String, String>`里的键值对会被添加到`HttpGet`的头信息中。注意,在实际使用后别忘了关闭`CloseableHttpResponse`和`CloseableHttpClient`,以释放资源:
```java
try {
CloseableHttpResponse response = sendGetWithHeaders(url, headers);
HttpEntity entity = response.getEntity();
// ...处理响应内容...
EntityUtils.consume(entity); // 关闭实体
response.close(); // 关闭响应
} finally {
httpClient.close(); // 关闭HttpClient
}
```
阅读全文