参考:https://www.cnblogs.com/honeybee/p/7879705.html
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));