HttpClient4.X发送Get请求的url参数拼接

Posted 丹江湖畔养蜂子的赵大爹

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient4.X发送Get请求的url参数拼接相关的知识,希望对你有一定的参考价值。

HttpClient4.X发送Get请求的参数拼接

使用httpClient发送get请求时,请求参数可以以?key=val&key1=val1的拼接到url后面。
但是请求参数较多时,这种方法比较麻烦,也不太优雅;研究了一下发现HttpClient4.X本身
是支持处理参数的。

1. 使用 URIBuilder来构建请求URI

httpclient相关的jar包mvn依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.3</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>
import com.google.common.collect.Lists;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

    private HttpGet buildHttpGet(String url, Map<String, String> para)
            throws URISyntaxException {
        URIBuilder builder = new URIBuilder(url);
        Set<String> set = para.keySet();
        for(String key: set){
            builder.setParameter(key, para.get(key));
        }
        HttpGet request = new HttpGet(builder.build());
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(6000)
                .setConnectTimeout(6000)
                .setConnectionRequestTimeout(6000).build();
        request.setConfig(requestConfig);
        System.out.println(request.getURI().toString());
        return request;
    }

2. 使用 NameValuePair 来拼接URI

List<NameValuePair> params = Lists.newArrayList();
params.add(new BasicNameValuePair("cityEname", "henan"));
String str = "";
//转换为键值对
str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
System.out.println(str);
HttpGet httpGet = new HttpGet(url + "?" + str);

3. 根据 HttpGet反向获取键值对列表

HttpGet request = new HttpGet("http://example.com/?var=1&var=2");
URIBuilder newBuilder = new URIBuilder(request.getURI());
//获取键值对列表
List<NameValuePair> params = newBuilder.getQueryParams();
//转换为键值对字符串
String str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));

以上是关于HttpClient4.X发送Get请求的url参数拼接的主要内容,如果未能解决你的问题,请参考以下文章

get请求中url传参中文乱码问题

get请求中url传参中文乱码问题--集锦

postman使用get请求的url地址传参中文乱码问题

关于httpclient 请求https (如何绕过证书验证)

axios笔记

GET/POST/g和钩子函数(hook)