httpclient4.x to send a GET request for parameter stitching
When sending a GET request using HttpClient, the request parameter can be Key=val&key1=val1 the stitching to the back of the URL.
But when the request parameter is more, this method is more troublesome, not too elegant; and studied the discovery of httpclient4.x itself
is to support processing parameters.
1. Using UriBuilder to build the request URI
HttpClient-related jar package MVN dependencies:
<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 {URI Builder 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. Use Namevaluepair to stitch URIs
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. Reverse the list of key-value pairs based on 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 URL parameter stitching for send GET request