Encapsulating httpclient for HTTP requests and HTTPS requests

Source: Internet
Author: User
Tags http post

One. HTTPS ignores certificates

/*** HttpClient for HTTPS requests * *@authorJoey **/ Public classsslclient { Public Staticcloseablehttpclient Createsslclientdefault () {Try{sslcontext Sslcontext=NewSslcontextbuilder (). Loadtrustmaterial (NULL,NewTruststrategy () {//Trust all                 Public BooleanIsTrusted (x509certificate[] chain, String authtype)throwscertificateexception {return true;            }}). Build (); Sslconnectionsocketfactory SSLSF=Newsslconnectionsocketfactory (Sslcontext); returnHttpclients.custom (). Setsslsocketfactory (SSLSF). build (); } Catch(keymanagementexception e) {e.printstacktrace (); } Catch(nosuchalgorithmexception e) {e.printstacktrace (); } Catch(keystoreexception e) {e.printstacktrace (); }        returnHttpclients.createdefault (); }}

Two. Post and GET requests

/*** Using HttpClient's tool class * *@authorJoey **/ Public classHttpclientutil {Private StaticString CharSet = "UTF-8"; Private StaticCloseablehttpclient httpClient =NULL; Private StaticCloseablehttpresponse response =NULL; /*** POST request for HTTPS *@paramURL *@paramJsonstr *@paramCharSet *@return     */     Public Staticstring dohttpspost (string url, string jsonstr) {Try{httpClient=Sslclient.createsslclientdefault (); HttpPost HttpPost=Newhttppost (URL); Httppost.setheader ("Content-type", "Application/json"); Stringentity SE=Newstringentity (JSONSTR); Se.setcontenttype ("Text/json"); Se.setcontentencoding (NewBasicheader ("Content-type", "Application/json"));                        Httppost.setentity (SE); Response=Httpclient.execute (HttpPost); if(Response! =NULL) {httpentity resentity=response.getentity (); if(Resentity! =NULL) {                    returnentityutils.tostring (resentity, CharSet); }            }        } Catch(Exception ex) {ex.printstacktrace (); }finally {             if(HttpClient! =NULL){                    Try{httpclient.close (); } Catch(IOException e) {e.printstacktrace (); }                }                if(Response! =NULL){                    Try{response.close (); } Catch(IOException e) {e.printstacktrace (); }                }        }        return NULL; }        /*** HTTP POST request (Parameters for Key-value format) *@paramURL *@paramparam *@return     */     Public StaticString Dohttppost (String url,map<string,string>param) {        Try {            //request to initiate clientHttpClient =Httpclients.createdefault (); //Parameter CollectionList<namevaluepair> Postparams =NewArraylist<namevaluepair>(); //traversing parameters and adding to the collection             for(Map.entry<string, string>Entry:param.entrySet ()) {Postparams.add (NewBasicnamevaluepair (Entry.getkey (), Entry.getvalue ())); }                        //access via postHttpPost post =Newhttppost (URL); Httpentity paramentity=Newurlencodedformentity (Postparams,charset);            Post.setentity (paramentity); Response=Httpclient.execute (POST); Statusline Status=Response.getstatusline (); intState =Status.getstatuscode (); if(state = =HTTPSTATUS.SC_OK) {httpentity valueentity=response.getentity (); String content=entityutils.tostring (valueentity); //jsonobject = jsonobject.fromobject (content);                returncontent; }        } Catch(unsupportedencodingexception e) {e.printstacktrace (); } Catch(clientprotocolexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally{            if(HttpClient! =NULL){                Try{httpclient.close (); } Catch(IOException e) {e.printstacktrace (); }            }            if(Response! =NULL){                Try{response.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }        return NULL; }         /*** HTTP POST request (to request JSON-formatted parameters) *@paramURL *@paramparams *@return      */       Public Staticstring dohttppost (string url, string jsonstr) {Try{httpClient=Httpclients.createdefault (); //Create HttpPostHttpPost HttpPost =Newhttppost (URL); Httppost.setheader ("Accept", "Application/json"); Stringentity Entity=Newstringentity (Jsonstr, CharSet); Entity.setcontenttype ("Text/json"); Entity.setcontentencoding (NewBasicheader ("Content-type", "Application/json"));                      Httppost.setentity (entity); //send a POST requestResponse =Httpclient.execute (HttpPost); if(Response.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {httpentity responseentity=response.getentity (); String jsonstring=entityutils.tostring (responseentity); returnjsonstring; }        }Catch(Exception e) {e.printstacktrace (); }finally {            if(HttpClient! =NULL){                Try{httpclient.close (); } Catch(IOException e) {e.printstacktrace (); }            }            if(Response! =NULL){                Try{response.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }          return NULL; }          /*** HTTP GET request *@paramURL *@paramparam *@return     */     Public StaticString Dohttpget (String url,map<string,string>param) {closeablehttpclient httpclient=NULL; Closeablehttpresponse Response=NULL; Try{httpclient=Httpclients.createdefault (); if(param! =NULL&&!Param.isempty ()) {                //Parameter CollectionList<namevaluepair> Getparams =NewArraylist<namevaluepair>();  for(Map.entry<string, string>Entry:param.entrySet ()) {Getparams.add (NewBasicnamevaluepair (Entry.getkey (), Entry.getvalue ())); } URL+="?" +entityutils.tostring (NewUrlencodedformentity (Getparams), "UTF-8"); }            //Send Gey RequestHttpGet HttpGet =Newhttpget (URL); Response=Httpclient.execute (HttpGet); if(Response.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {                  returnentityutils.tostring (Response.getentity ()); }         }Catch(Exception e) {e.printstacktrace (); }finally{            if(HttpClient! =NULL){                Try{httpclient.close (); } Catch(IOException e) {e.printstacktrace (); }            }            if(Response! =NULL){                Try{response.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }        return NULL; }    }
View Code

Encapsulating httpclient for HTTP requests and HTTPS requests

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.