CloseableHttpClient带参数和可设置请求头
时间: 2023-10-14 08:40:46 浏览: 161
好的,以下是使用CloseableHttpClient发送带参数和可设置请求头的GET请求的示例代码:
```java
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpGetWithParamsAndHeaders {
public static void main(String[] args) throws Exception {
String url = "http://www.example.com/api";
Map<String, String> params = new HashMap<String, String>();
params.put("param1", "value1");
params.put("param2", "value2");
// 对参数进行URL编码
String query = getQuery(params);
// 创建URIBuilder对象
URIBuilder uriBuilder = new URIBuilder(url);
uriBuilder.setQuery(query);
// 创建HttpGet对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
// 设置请求头
httpGet.addHeader("User-Agent", "Mozilla/5.0");
httpGet.addHeader("Accept-Language", "en-US,en;q=0.5");
// 创建CloseableHttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 发送请求
CloseableHttpResponse response = httpClient.execute(httpGet);
// 处理响应
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseString = EntityUtils.toString(entity);
System.out.println(responseString);
}
} finally {
response.close();
}
}
private static String getQuery(Map<String, String> params) throws IOException {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
result.append("&");
}
String query = result.toString();
return query.length() > 0 ? query.substring(0, query.length() - 1) : query;
}
}
```
在上面的代码中,我们首先定义了一个URL和一个Map类型的参数params。然后使用getQuery方法将参数拼接成请求URL的查询字符串。接着,我们创建了一个URIBuilder对象,并将查询字符串设置为URI的查询部分。然后,我们创建了一个HttpGet对象,并使用addHeader方法设置了请求头。最后,我们创建了一个CloseableHttpClient对象,并使用execute方法发送请求,并处理响应结果。
需要注意的是,上述代码中的URL和参数都是示例数据,实际使用时需要替换成相应的值。另外,如果请求的参数比较多,可以使用Map来存储参数,然后遍历Map来拼接请求URL的查询字符串。
阅读全文