httpclient version 4.1
send a POST request
Public StaticJsonobject Post (String url,jsonobject JSON) {HttpClient client=Newdefaulthttpclient (); HttpPost Post=Newhttppost (URL); Jsonobject Response=NULL; Try{stringentity s=Newstringentity (json.tostring ()); S.setcontentencoding ("UTF-8"); S.setcontenttype ("Application/json"); Post.setentity (s); HttpResponse Res=Client.execute (POST); if(Res.getstatusline (). Getstatuscode () = =HttpStatus.OK.value ()) {httpentity entity=res.getentity (); String CharSet=Entityutils.getcontentcharset (entity); Response=NewJsonobject (NewJsontokener (NewInputStreamReader (Entity.getcontent (), CharSet)); } } Catch(Exception e) {Throw NewRuntimeException (e); } returnresponse; }
Simulation Submission Form:
Private StaticHttpPost postform (String URL, map<string, string>params) {HttpPost Httpost=Newhttppost (URL); List<NameValuePair> Nvps =NewArrayList <NameValuePair>(); Set<String> KeySet =Params.keyset (); for(String key:keyset) {Nvps.add (NewBasicnamevaluepair (Key, Params.get (key)); } Try{log.info ("Set Utf-8 form entity to HttpPost"); Httpost.setentity (Newurlencodedformentity (Nvps, HTTP. Utf_8)); } Catch(unsupportedencodingexception e) {e.printstacktrace (); } returnHttpost; }
GET request
Public Static string get (string url) { new defaulthttpclient (); NULL ; Log.info ("Create HttpPost:" + URL); New httpget (URL); = Invoke (httpclient, get); Httpclient.getconnectionmanager (). shutdown (); return body; }
To initiate a POST request, set the timeout:
It is important to note that the APIs for each version setting timeout are not the same.
It is also important to note that the timeout in 3:
1, Connection timeout: ConnectionTimeout refers to the connection waiting time for connecting a URL.
2, read data timeout: SoTimeout refers to the connection of the previous URL, get response return wait time
3,sockettimeout: Defines the timeout period for socket read data, which is the time to wait for the response data to be fetched from the server
Public Staticstring sendpostrequest (string url, String str, string ContentType, String charset) {//httpparams httpparams = new Basichttpparams ();//version 4.1//httpconnectionparams.setconnectiontimeout (Httpparams,);//Establish connection timeout, prevent call URL to dead chain, consume server IO//httpconnectionparams.setsotimeout (Httpparams, n);//Response Timeout//closeablehttpclient httpClient = new Defaulthttpclient ();Requestconfig.builder Requestbuilder = Requestconfig.custom ();//4.3. Version 5Requestbuilder = Requestbuilder.setconnecttimeout (5000); //Requestbuilder = requestbuilder.setconnectionrequesttimeout (+);Httpclientbuilder Builder=httpclientbuilder.create (); Builder.setdefaultrequestconfig (Requestbuilder.build ()); Closeablehttpclient httpClient=Builder.build (); HttpPost Post=Newhttppost (URL); //requestconfig requestconfig = Requestconfig.custom (). SetSocketTimeout (.). Setconnecttimeout (+). Build (); //Post.setconfig (requestconfig);Post.setheader ("Content-type", ContentType); ResponseHandler<String> ResponseHandler =NewBasicresponsehandler (); String Response=NULL; Try{post.setentity (Newstringentity (str, CharSet)); LongStart =System.currenttimemillis (); Try{Response=Httpclient.execute (Post,responsehandler); } Catch(Exception connectiontimeoutexception) {//Establish connection Timeout exception Longp = System.currenttimemillis ()-start; Log.error ("Sendpostrequest has a connectiontimeoutexception timeout=>" + p + "" +URL); }finally{ //Httpclient.getconnectionmanager (). shutdown ();post.releaseconnection (); } } Catch(Exception e) {log.error ("An exception occurred when executing HTTP POST request + URL +"! ", E); } returnresponse; }
HttpClient send a request