HTTPS Communication Tool Class

Source: Internet
Author: User

Record an HTTPS communication tool class that is used in development and will be used later.

  

Certificate trust manager for HTTPS communication

Importjava.security.cert.CertificateException;Importjava.security.cert.X509Certificate;ImportJavax.net.ssl.X509TrustManager;/*** Certificate trust manager (for HTTPS requests)*/ Public classMyx509trustmanagerImplementsX509trustmanager {/*** Create by YYC June 27, 2017 morning 10:24:49*/@Override Public voidCheckclienttrusted (x509certificate[] arg0, String arg1)throwscertificateexception {//TODO auto-generated Method Stub            }    /*** Create by YYC June 27, 2017 morning 10:24:49*/@Override Public voidCheckservertrusted (x509certificate[] arg0, String arg1)throwscertificateexception {//TODO auto-generated Method Stub            }    /*** Create by YYC June 27, 2017 morning 10:24:49*/@Override Publicx509certificate[] Getacceptedissuers () {//TODO auto-generated Method Stub        return NULL; }  } 

HttpRequest method is used for HTTPS communication, method incoming request URL, the way of request (such as: Get,post), request to send data, etc.

ImportJava.io.BufferedReader;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;Importjava.net.ConnectException;ImportJava.net.URL;ImportJavax.net.ssl.HostnameVerifier;Importjavax.net.ssl.HttpsURLConnection;ImportJavax.net.ssl.SSLContext;Importjavax.net.ssl.SSLSession;ImportJavax.net.ssl.TrustManager;ImportOrg.apache.commons.httpclient.HttpStatus;/*** Write a tool class for initiating HTTPS requests Weixinnetworkutil access to the Network tool class*/ Public classWeixinnetworkutil {/*** Initiate HTTPS request * *@paramRequrl * Requested URL address *@paramRequestmethod * Method of Request *@paramOUTPUTSTR * Data submitted *@returnthe response string (which may be JSON, XML, or otherwise, but all string) HttpRequest method is to request an HTTPS address, * The parameter requestmethod is a string "GET" or "POST", pass null or     The default is get mode, * parameter outputstr is a string to commit, not "" or null, Requestmethod is "POST". */     Public Staticstring HttpRequest (String requrlstring, String Requestmethod, string outputstr) {URL url; Httpsurlconnection Conn=NULL; InputStream InputStream=NULL; InputStreamReader InputStreamReader=NULL; BufferedReader Bufferreader=NULL; StringBuffer Resultdata=NewStringBuffer (); Try {            //Create a URL resourceURL =NewURL (requrlstring); //establishing an HTTP connectionconn =(httpsurlconnection) url.openconnection (); //Create the Sslcontext object and initialize it with the trust manager that we specifiedTrustmanager[] TM = {NewMyx509trustmanager ()}; Sslcontext CTX= Sslcontext.getinstance ("SSL", "Sunjsse"); Ctx.init (NULLTmNewjava.security.SecureRandom ());            Conn.setsslsocketfactory (Ctx.getsocketfactory ()); Conn.sethostnameverifier (NewHostnameverifier () {@Override Public BooleanVerify (String arg0, sslsession arg1) {return true;            }            }); Conn.setdoinput (true);//allow input stream, that is, allow downloadConn.setdooutput (true);//allow output stream, i.e. allow uploadConn.setusecaches (false);//whether to use buffering            if(NULL! = Requestmethod &&! "". Equals (Requestmethod)) {Conn.setrequestmethod (requestmethod);//using the specified method}Else{Conn.setrequestmethod ("GET");//using GET Requests            }            //When there is data to be submitted            if(NULL! = Outputstr &&! "". Equals (OUTPUTSTR)) {OutputStream OutputStream=Conn.getoutputstream (); //Note the encoding format to prevent Chinese garbled charactersOutputstream.write (Outputstr.getbytes ("UTF-8"));                Outputstream.flush (); //Freeing Resources                if(OutputStream! =NULL) {outputstream.close (); OutputStream=NULL; }} conn.connect ();//Start connection Request//status of Request return            if(Conn.getresponsecode () = =HTTPSTATUS.SC_OK) {System.out.println ("HTTPS network connection succeeded, return code:" +Conn.getresponsecode ()); InputStream= Conn.getinputstream ();//Get input streamInputStreamReader =NewInputStreamReader (InputStream); Bufferreader=NewBufferedReader (InputStreamReader);                String Inputline;  while((Inputline = Bufferreader.readline ())! =NULL) {//converts the returned input flow to a stringResultdata.append (inputline + "\ n")); }                //Freeing Resources                if(Bufferreader! =NULL) {bufferreader.close (); Bufferreader=NULL; }                if(InputStreamReader! =NULL) {inputstreamreader.close (); InputStreamReader=NULL; }                if(InputStream! =NULL) {inputstream.close (); InputStream=NULL; }            }Else{System.out.println ("HTTPS Network connection error, error code:" +Conn.getresponsecode ()); }        } Catch(connectexception CE) {System.err.println ("Weixin Server connection timed out.");        Ce.printstacktrace (); } Catch(Exception e) {System.err.println ("HTTPS request error.");        E.printstacktrace (); } finally {            //disconnecting from the networkConn.disconnect (); }                returnresultdata.tostring (); }}

HTTPS Communication Tool Class

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.