Java Network connection HttpURLConnection, httpsurlconnection

Source: Internet
Author: User

The tool class consists of two methods: HTTP request, HTTPS request

Look directly at the code:

Package Com.jtools;import Java.io.bufferedreader;import Java.io.inputstream;import java.io.InputStreamReader; Import Java.io.outputstream;import java.net.connectexception;import Java.net.httpurlconnection;import Java.net.URL ; import Javax.net.ssl.httpsurlconnection;import Javax.net.ssl.sslcontext;import javax.net.ssl.SSLSocketFactory; Import javax.net.ssl.trustmanager;/** * HTTP Tool class * @author Json_wang*/public class Httputil {/** * * Initiate HTTP request and get results * @param r Equesturl Request Address * @param Requestmethod request Method (GET, POST) * @param outputstr submitted data Format (example: "Name=name&age=age")//Body, The text content actually with get URL in '? ' After the argument string is consistent * @return JSON string (the JSON format is either Jsonobject or Jsonarray, here is a string, then converted in the controller) */public static string HttpRequest (String Requesturl, String Requestmethod, String outputstr) {string resultstr = ""; StringBuffer buffer = new StringBuffer (); try {URL url = new URL (requesturl); HttpURLConnection httpurlconn = (httpurlconnection) url.openconnection (); Httpurlconn.setdooutput (true); Httpurlconn.setdOinput (True); Httpurlconn.setusecaches (false);//Set Request mode (Get/post) Httpurlconn.setrequestmethod (Requestmethod);// HttpURLConnection is based on the HTTP protocol, and its underlying is implemented via socket communication. If you do not set a timeout (timeout), in the case of a network exception, it may cause the program to zombie without continuing to execute httpurlconn.setconnecttimeout (30*1000);// 30s Timeout Httpurlconn.setreadtimeout (10*1000),//10s timeout/*//set request Properties Httpurlconn.setrequestproperty ("Content-type", "     Application/x-www-form-urlencoded ");    Httpurlconn.setrequestproperty ("Charset", "UTF-8"); *///httpurlconnection's connect () function actually just establishes a TCP connection to the server and does not actually send an HTTP request. The Get method requires an explicit connection if ("Get". Equalsignorecase (Requestmethod)) {Httpurlconn.connect ();} This post method implicitly automatically connects//when there is data to be submitted when the IF (null! = outputstr) {OutputStream outputstream = Httpurlconn.getoutputstream ();// Note the encoding format to prevent Chinese garbled outputstream.write (outputstr.getbytes ("UTF-8")); Outputstream.close ();} Convert the returned input stream to a string InputStream InputStream = Httpurlconn.getinputstream (); InputStreamReader InputStreamReader = new InputStreamReader (InputStream, "utf-8"); BufferedReader BufferedReader = new BufferedreadeR (InputStreamReader); String str = null;while ((str = bufferedreader.readline ()) = null) {buffer.append (str);} Bufferedreader.close (); Inputstreamreader.close ();//Release Resource Inputstream.close (); inputstream = null; Httpurlconn.disconnect (); resultstr = Buffer.tostring ();} catch (connectexception CE) {System.out.println ("Server connection timed out.");} catch (Exception e) { System.out.println (requesturl+ "Request error:\n" +e); return resultstr;} /** * Initiate HTTPS request and get results * * @param requesturl Request address * @param Requestmethod request (GET, POST) * @param outputstr submitted data Format (example Sub: "Name=name&age=age")//body, body content in fact with Get URL '? ' After the argument string is consistent * @return JSON string (the JSON format is either Jsonobject or Jsonarray, here is a string, then converted in the controller) */public static string Httpsrequest (String Requesturl, String Requestmethod, String outputstr) {string resultstr = ""; StringBuffer buffer = new StringBuffer (); try {//Create Sslcontext object and initialize trustmanager[with our specified trust Manager] TM = {New Myx509trustmana GER ()}; Sslcontext Sslcontext = sslcontext.getinstance ("SSL "," Sunjsse "); Sslcontext.init (NULL, TM, New Java.security.SecureRandom ());// Sslsocketfactory object Sslsocketfactory SSF = Sslcontext.getsocketfactory () obtained from the above Sslcontext object; URL url = new URL (requesturl); Httpsurlconnection httpurlconn = (httpsurlconnection) url.openconnection (); httpurlconn.setsslsocketfactory (SSF); Httpurlconn.setdooutput (True); Httpurlconn.setdoinput (true); Httpurlconn.setusecaches (false);//Set Request mode (get/ POST) Httpurlconn.setrequestmethod (Requestmethod),//httpurlconnection is based on the HTTP protocol, and its underlying is implemented via socket communication. If you do not set a timeout (timeout), in the case of a network exception, it may cause the program to zombie without continuing to execute httpurlconn.setconnecttimeout (30*1000);// 30s Timeout Httpurlconn.setreadtimeout (10*1000),//10s timeout/*//set request Properties Httpurlconn.setrequestproperty ("Content-type", "     Application/x-www-form-urlencoded ");    Httpurlconn.setrequestproperty ("Charset", "UTF-8"); *///httpurlconnection's connect () function actually just establishes a TCP connection to the server and does not actually send an HTTP request. The Get method requires an explicit connection if ("Get". Equalsignorecase (Requestmethod)) {Httpurlconn.connect ();} This post method implicitly automatically connects//when there is data to be submitted when the IF (null! = OutPUTSTR) {OutputStream outputstream = Httpurlconn.getoutputstream ();//Note the encoding format to prevent Chinese garbled outputstream.write ( Outputstr.getbytes ("UTF-8")); Outputstream.close ();} Convert the returned input stream to a string InputStream InputStream = Httpurlconn.getinputstream (); InputStreamReader InputStreamReader = new InputStreamReader (InputStream, "utf-8"); BufferedReader BufferedReader = new BufferedReader (InputStreamReader); String str = null;while ((str = bufferedreader.readline ()) = null) {buffer.append (str);} Bufferedreader.close (); Inputstreamreader.close ();//Release Resource Inputstream.close (); inputstream = null; Httpurlconn.disconnect (); resultstr = Buffer.tostring ();} catch (connectexception CE) {System.out.println ("Server connection timed out.");} catch (Exception e) { System.out.println (requesturl+ "Request error:\n" +e); return resultstr;} public static void Main (string[] args) {System.out.println (HttpRequest ("https://www.zhihu.com/", "GET", null));}}

Auxiliary classes:

Package Com.jtools;import Java.security.cert.certificateexception;import java.security.cert.X509Certificate; Import javax.net.ssl.x509trustmanager;/** * Certificate trust manager (for HTTPS requests) */public class Myx509trustmanager implements X509trustmanager {public void checkclienttrusted (x509certificate[] chain, String authtype) throws Certificateexception {}public void checkservertrusted (x509certificate[] chain, String authtype) throws Certificateexception {}public X509certificate[] Getacceptedissuers () {return null;}}

Attached: source code:https://github.com/JsonShare/JTools

Ps:java Network Connection HttpURLConnection and httpclient difference and contact http://blog.csdn.net/wszxl492719760/article/details/8522714

Java Network connection HttpURLConnection, httpsurlconnection

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.