CloseableHttpClient 设置get请求的入参
时间: 2023-10-14 22:40:30 浏览: 44
对于 CloseableHttpClient 的 GET 请求,可以通过构造请求参数的方式进行设置。以下是一个设置 GET 请求参数的示例:
```
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com/path");
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
String paramString = URLEncodedUtils.format(params, "UTF-8");
httpGet.setURI(URI.create("http://example.com/path?" + paramString));
CloseableHttpResponse response = httpClient.execute(httpGet);
```
在上面的示例中,我们首先创建了一个 CloseableHttpClient 对象 httpClient 和一个 HttpGet 对象 httpGet,然后创建了一个 List 对象 params,并添加了两个参数。接着使用 URLEncodedUtils 类将参数编码成字符串 paramString,将其添加到请求 URL 中,最后通过 httpClient.execute(httpGet) 方法发送请求并获取响应。
请注意,需要使用 URLEncodedUtils 类对参数进行编码,这是因为 HTTP GET 请求将参数编码为 URL 查询字符串,而查询字符串中的参数需要进行 URL 编码。 URLEncodedUtils.format() 方法可以将参数编码为 URL 查询字符串。