Java HTTP Request Tool class code (HTTPS supported)

Source: Internet
Author: User

 Packagecom.guyezhai.modules.utils;ImportJava.io.BufferedReader;ImportJava.io.DataOutputStream;Importjava.io.IOException;ImportJava.io.InputStreamReader;Importjava.net.HttpURLConnection;ImportJava.net.URL;ImportJava.net.URLEncoder;Importjava.security.cert.X509Certificate;ImportJava.util.Map;ImportJava.util.Map.Entry;ImportJavax.net.ssl.HostnameVerifier;Importjavax.net.ssl.HttpsURLConnection;ImportJavax.net.ssl.SSLContext;Importjavax.net.ssl.SSLSession;ImportJavax.net.ssl.X509TrustManager; Public classHttputils {/*** POST Request Remote HTTP page * *@paramcontentURL *@paramparams *@return     */     Public StaticString post (String contentURL, map<string, object>params) {StringBuilder Contentbuilder=NewStringBuilder (); HttpURLConnection Connection=NULL; DataOutputStream out=NULL; BufferedReader Reader=NULL; Try{Connection= (httpurlconnection)NewURL (contentURL). OpenConnection (); //set the socket timeoutConnection.setconnecttimeout (10000); Connection.setreadtimeout (20000); //The Post request cannot use the cacheConnection.setusecaches (false); //Urlconnection.setinstancefollowredirects is a member function and is used only for the current functionConnection.setinstancefollowredirects (true); Connection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); Connection.setrequestmethod ("POST"); Connection.setdooutput (true);//whether to enter parameters//It is important to note that Connection.getoutputstream will implicitly connectConnection.connect (); out=NewDataOutputStream (Connection.getoutputstream ()); StringBuilder Parambbuilder=NewStringBuilder (); if(Params! =NULL) {                 for(Entry<string, object>E:params.entryset ()) {Parambbuilder.append (E.getkey ()). Append ("="). Append (Urlencoder.encode (string.valueof (E.getvalue ()), "UTF-8")). Append ("&"); } Parambbuilder.deletecharat (Parambbuilder.length ()-1); }            //Dataoutputstream.writebytes writes a 16-bit Unicode character in a string as a 8-bit character in the streamout.writebytes (parambbuilder.tostring ());                        Out.flush (); Reader=NewBufferedReader (NewInputStreamReader (Connection.getinputstream (), "UTF-8")); intBuffer = 0;  while(buffer = Reader.read ())! =-1) {contentbuilder.append (Char) (buffer); }                    } Catch(Exception e) {//Exception Handling}finally {            if(Out! =NULL) {                Try{out.close (); } Catch(IOException E1) {e1.printstacktrace (); }            }            if(Reader! =NULL) {                Try{reader.close (); } Catch(IOException E1) {e1.printstacktrace (); }            }                        if(Connection! =NULL) {connection.disconnect (); }        }        returncontentbuilder.tostring (); }        /*** Get Method Request * *@paramcontentURL *@return     */     Public Staticstring Get (String contenturl) {StringBuilder Contentbuilder=NewStringBuilder (); HttpURLConnection Connection=NULL; BufferedReader Reader=NULL; Try{Connection= (httpurlconnection)NewURL (contentURL). OpenConnection (); //set the socket timeoutConnection.setconnecttimeout (10000); Connection.setreadtimeout (20000); Connection.setrequestmethod ("GET");                        Connection.connect (); Reader=NewBufferedReader (NewInputStreamReader (Connection.getinputstream (), "UTF-8")); intBuffer = 0;  while(buffer = Reader.read ())! =-1) {contentbuilder.append (Char) (buffer); }        } Catch(Exception e) {//Exception Handling}finally {            if(Reader! =NULL) {                Try{reader.close (); } Catch(IOException E1) {e1.printstacktrace (); }            }            if(Connection! =NULL) {connection.disconnect (); }        }        returncontentbuilder.tostring (); }        /*** POST Request Remote HTTPS page * *@paramcontentURL *@paramparams *@return     */     Public StaticString Posthttps (String contentURL, map<string, object>params) {StringBuilder Contentbuilder=NewStringBuilder (); Httpsurlconnection Connection=NULL; DataOutputStream out=NULL; BufferedReader Reader=NULL; Try{hostnameverifier HNV=NewHostnameverifier () {@Override Public BooleanVerify (String hostname, sslsession session) {return true;                        }            }; X509trustmanager TrustManager=NewX509trustmanager () {@Override Publicx509certificate[] Getacceptedissuers () {return NULL; } @Override Public voidcheckservertrusted (x509certificate[] chain, String authtype) {} @Overr IDE Public voidcheckclienttrusted (x509certificate[] chain, String authtype) {}}; X509trustmanager[] Xtmarray=Newx509trustmanager[] {TrustManager}; Sslcontext Sslcontext= Sslcontext.getinstance ("TLS"); Sslcontext.init (NULL, Xtmarray,Newjava.security.SecureRandom ()); if(Sslcontext! =NULL) {httpsurlconnection.setdefaultsslsocketfactory (Sslcontext.getsocketfactory ());                        } httpsurlconnection.setdefaulthostnameverifier (HNV); Connection= (httpsurlconnection)NewURL (contentURL). OpenConnection (); //set the socket timeoutConnection.setconnecttimeout (10000); Connection.setreadtimeout (20000); //The Post request cannot use the cacheConnection.setusecaches (false); //Urlconnection.setinstancefollowredirects is a member function and is used only for the current functionConnection.setinstancefollowredirects (true); Connection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); Connection.setrequestmethod ("POST"); Connection.setdooutput (true);//whether to enter parametersConnection.connect (); out=NewDataOutputStream (Connection.getoutputstream ()); StringBuilder Parambbuilder=NewStringBuilder (); if(Params! =NULL) {                 for(Entry<string, object>E:params.entryset ()) {Parambbuilder.append (E.getkey ()). Append ("="). Append (Urlencoder.encode (string.valueof (E.getvalue ()), "UTF-8")). Append ("&"); } Parambbuilder.deletecharat (Parambbuilder.length ()-1); }            //Dataoutputstream.writebytes writes a 16-bit Unicode character in a string as a 8-bit character in the streamout.writebytes (parambbuilder.tostring ());                        Out.flush (); Reader=NewBufferedReader (NewInputStreamReader (Connection.getinputstream (), "UTF-8")); intBuffer = 0;  while(buffer = Reader.read ())! =-1) {contentbuilder.append (Char) (buffer); }        } Catch(Exception e) {//Exception Handling}finally {            if(Out! =NULL) {                Try{out.close (); } Catch(IOException E1) {e1.printstacktrace (); }            }            if(Reader! =NULL) {                Try{reader.close (); } Catch(IOException E1) {e1.printstacktrace (); }            }            if(Connection! =NULL) {connection.disconnect (); }        }        returncontentbuilder.tostring (); }    }

Java HTTP Request Tool class code (HTTPS supported)

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.