The use of Android-class httpurlconnection

Source: Internet
Author: User
<span id="Label3"></p> <ol> <ol> <li><p>Get HttpURLConnection Object<br></p></li> </ol> </ol> <pre class="brush:java;toolbar: true; auto-links: false;"><pre class="brush:java;toolbar: true; auto-links: false;">URL url = new URL (url);  URLConnection rulconnection = url.openconnection (); The URLConnection object here is actually the subclass httpurlconnection of the URLConnection Class//that is generated based on the Url's//request protocol (here http), so it's best to Convert//to Httpurlconne Ction object of type, in order to use//httpurlconnection more apis. as follows: httpurlconnection httpurlconnection = (httpurlconnection) rulconnect Ion</pre></pre> <p><p>2. Setting <span style="font-size: 13.3333339691162px; line-height: 24.0000019073486px;">parameters for HttpURLConnection objects</span></p></p> <pre class="brush:java;toolbar: true; auto-links: false;">  Set whether to output to httpurlconnection, because this is a post request, the parameters are placed inside the    // http body, so it needs to be set to true,  False;       httpurlconnection.setdooutput (true) by default;    //   Set whether to read from httpurlconnection, true;        by default Httpurlconnection.setdoinput (true);    //post  Request cannot use cache         httpurlconnection.setusecaches (false);     //  Sets the content type to be serialized as a Java object    //  (if This is not the case, when the serialized object is transferred, the Web service may throw java.io.EOFException when the default is not this Type)         httpurlconnection.setrequestproperty ("content-type",  "application/ X-java-serialized-object ");    //  the method for setting the request is" POST ", The default is get        httpurlconnection.setrequestmethod ("POST");    //  connection, The configuration url.openconnection () from 2nd above must be completed before connect,       Httpurlconnection.connect (); </pre> <p><p><span style="font-size: 13.3333339691162px; line-height: 24.0000019073486px;"></span>3.HttpURLConnection Connection</p></p> <pre class="brush:java;toolbar: true; auto-links: false;"><pre class="brush:java;toolbar: true; auto-links: false;">Here Getoutputstream will implicitly connect (that is, just like calling the Connect () method above,//so It is not possible to call the above connect () in development). OutputStream OUTSTRM = Httpurlconnection.getoutputstream ();</pre></pre> <p><p>4. Data reading and writing process<br></p></p> <pre class="brush:java;toolbar: true; auto-links: false;">  Now constructs an object output stream object from the output stream object to implement the output serializable Object.     objectoutputstream objoutputstrm = new objectoutputstream (outStrm) ;    //  writes out data to the object output stream, which is stored in the memory buffer     objoutputstrm.writeobject (new  string ("i am Test data");    //  refreshes the object output stream, writes any bytes to the potential stream (some of them are Objectoutputstream)      objoutputstm.flush ();     //  closes the stream object. At this point, no more data can be written to the object output stream, the previously written data exists in the memory buffer,   //  the prepared HTTP request is formally sent to the server when the getInputStream () function is called below     objoutputstm.close ();   //  calls the getinputstream of the HttpURLConnection Connection object ( the,   //  function sends a complete HTTP request message encapsulated in the memory buffer to the Server.     inputstream instrm = httpconn.getinputstream ();  // <=== Note that The code snippet that actually sends the request is here    //  the Httpconn.getinputstream () method above has been called, the HTTP request has ended, and the output of the Bottom-to-object output stream is meaningless,//  Even if the object output stream does not call the close () method, The bottom operation does not write any data to the object output Stream.    //  therefore, to resend the data, you need to recreate the connection, reset the parameters, recreate the stream object, re-write the data,    //  resend the data (as to whether you need to re-examine these operations Again)      objoutputstm.writeobject (new string (""));     Httpconn.getinputstream ()</pre> <p style="font-size: 14px; white-space: normal; color: rgb(57, 57, 57); line-height: 21px; padding-top: 0px; padding-bottom: 0px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; margin-top: 10px !important; margin-right: auto !important; margin-left: auto !important; background-color: rgb(255, 255, 255);"><p style="font-size: 14px; white-space: normal; color: rgb(57, 57, 57); line-height: 21px; padding-top: 0px; padding-bottom: 0px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; margin-top: 10px !important; margin-right: auto !important; margin-left: auto !important; background-color: rgb(255, 255, 255);">Summary: a:) The Connect () function of HttpURLConnection actually only establishes a TCP connection to the server and does not actually send an HTTP Request.</p></p> <p style="font-size: 14px; white-space: normal; color: rgb(57, 57, 57); line-height: 21px; padding-top: 0px; padding-bottom: 0px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; margin-top: 10px !important; margin-right: auto !important; margin-left: auto !important; background-color: rgb(255, 255, 255);">Either the post or the Get,http request is actually sent out until the httpurlconnection getinputstream () Function.<br>B:) When sending a URL request by post, the URL request parameters are set in the order of the most heavy,<br>All configuration of the connection object (that heap of Set Functions)<br>Must be completed before the Connect () function Executes. The write operation to OutputStream must be preceded by the InputStream read Operation.<br>These orders are actually determined by the format of the HTTP Request.<br>If the InputStream read operation precedes the write operation of outputstream, an exception is thrown:<br>Java.net.ProtocolException:Cannot write output after reading input ....<br><br>C:) The HTTP request actually consists of two parts,<br>One is the HTTP header, and all the configuration about this HTTP request is defined in the HTTP header,<br>One is the text Content.<br>The Connect () function generates HTTP header information based on the configuration values of the HttpURLConnection object, so before calling the connect function, the<br>You have to get all the configurations Ready.<br>D:) After the HTTP header is followed by the body of the HTTP request, the content of the body is written through the OutputStream stream,<br>In fact, OutputStream is not a network stream, at best a string stream, and what is written into it is not immediately sent to the network,<br>instead, it exists in the memory buffer, and the HTTP body is generated based on what is entered when the OutputStream stream is Closed.<br>At this point, the HTTP request is ready for everything. When the getInputStream () function is called, the prepared HTTP request is<br>is officially sent to the server, and then an input stream is returned to read the Server's return information for this HTTP Request. Because the HTTP<br>The request was sent out at getInputStream (including the HTTP header and body), so the getInputStream () function<br>The connection object is then set (modification of the HTTP header Information) or written to OutputStream (the body is modified)<br>Is meaningless, performing these operations can cause an exception to Occur.<br><br>6:> servlet Side Development note:<br>A:) For the HTTP request of the Post type sent by the client, the servlet must implement the Dopost method instead of the Doget method.<br>B:) Use the HttpServletRequest getInputStream () method to obtain InputStream objects, such as:<br>InputStream instream = Httprequest.getinputstream ();<br>Now call Instream.available () (the method used to "return this input to the stream" where a method call can be unblocked<br>The estimated number of bytes read (or skipped) from this input stream is always reversed back to 0. An attempt was made to allocate a buffer using the return value of this method.<br>It is incorrect to save all the data in this Stream. so, the solution now is<br>This end of the servlet is implemented as Follows:<br>InputStream instream = Httprequest.getinputstream ();<br>ObjectInputStream objinstream = new ObjectInputStream (instream);<br>Object obj = Objinstream.readobject ();<br>Do the follow-up processing<br>。。。。。。<br>。。。 。。。<br>The client, regardless of whether the actual data is sent or not, is written to an object (which is afraid of this object), such as:<br>ObjectOutputStream OBJOUTPUTSTRM = new ObjectOutputStream (outstrm);<br>Objoutputstrm.writeobject (new String ("")); Send an empty data here<br>You can even send a null object, and the service end is taken and then Processed.<br>Objoutputstrm.writeobject (null);<br>Objoutputstrm.flush ();<br>Objoutputstrm.close ();<br><br>Note: When you create an object output stream objectoutputstream, the input stream that is taken from HttpServletRequest<br>(i.e., OUTSTRM in New ObjectOutputStream (outstrm) is wrapped in a bufferedoutputstream flow,<br>Must have Objoutputstrm.flush (); this sentence, in order to brush the flow information into the buffered output Stream.<br>ObjectOutputStream OBJOUTPUTSTRM = new ObjectOutputStream (new bufferedoutputstream (outstrm));<br>Objoutputstrm.writeobject (null);<br>Objoutputstrm.flush (); <====== must have it here.<br>Objoutputstrm.close ();<br><br>HttpURLConnection is based on the HTTP protocol, and its underlying is implemented via socket Communication. If you do not set a time-out (timeout), in the case of a network exception, it may cause the program to zombie without continuing to Execute. The corresponding timeout can be set by the following two statements:<br>System.setproperty ("sun.net.client.defaultConnectTimeout", time-out number of milliseconds string);<br>System.setproperty ("sun.net.client.defaultReadTimeout", time-out number of milliseconds string);<br><br><br>Where: sun.net.client.defaultConnectTimeout: time-out for connecting the host (in Milliseconds)<br>Sun.net.client.defaultReadTimeout: Timeout (in Milliseconds) to read data from the host<br><br>For example:<br>System.setproperty ("sun.net.client.defaultConnectTimeout", "30000");<br>System.setproperty ("sun.net.client.defaultReadTime<br><br>In java, you can use HttpURLConnection to request Web Resources.<br>The HttpURLConnection object cannot be constructed directly and needs to be url.openconnection () to obtain the HttpURLConnection object, as shown in the example code:</p> <pre><p><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 128); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 128); line-height: 1.5 !important;">1</span></span> <span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">String Szurl</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">=</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"> </span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">"</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">http://www.ee2ee.com/</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">"</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">;<br></span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 128); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 128); line-height: 1.5 !important;">2</span></span> <span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">URL url</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">=</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"> </span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 255); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 255); line-height: 1.5 !important;">New</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">URL (szurl);<br></span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 128); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 128); line-height: 1.5 !important;">3</span></span> <span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">httpurlconnection Urlcon</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">=</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">(httpurlconnection) url.openconnection (); </span></span></p></pre> <p><br><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">HttpURLConnection is based on the HTTP protocol, and its underlying is implemented via socket Communication. If you do not set a time-out (timeout), in the case of a network exception, it may cause the program to zombie without continuing to Execute. The corresponding timeout can be set by the following two statements:</span></span><br><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">System.setproperty ("sun.net.client.defaultConnectTimeout", time-out number of milliseconds string);</span></span><br><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">System.setproperty ("sun.net.client.defaultReadTimeout", time-out number of milliseconds string);</span></span><br><br><br><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">where: sun.net.client.defaultConnectTimeout: time-out for connecting the host (in Milliseconds)</span></span><br><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">sun.net.client.defaultReadTimeout: Timeout (in milliseconds) to read data from the host</span></span><br><br><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">for Example:</span></span><br><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">system.setproperty ("sun.net.client.defaultConnectTimeout", "30000");</span></span><br><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">system.setproperty ("sun.net.client.defaultReadTimeout", "30000");</span></span><br><br><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">prior to JDK 1.5, you can only control network timeouts by setting these two system Properties. In 1.5, you can also use the following two methods of Httpurlconnection's parent class Urlconnection:</span></span><br><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">setconnecttimeout: Setting the connection host timeout (in Milliseconds)</span></span><br><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">setreadtimeout: Setting read data timeout from host (in Milliseconds)</span></span><br><br><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">for Example:</span></span><br></p> <pre><p><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 128); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 128); line-height: 1.5 !important;">1</span></span> <span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">httpurlconnection Urlcon</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">=</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">(httpurlconnection) url.openconnection ();<br></span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 128); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 128); line-height: 1.5 !important;">2</span></span> <span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">Urlcon.setconnecttimeout (</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">30000</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">);<br></span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 128); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 128); line-height: 1.5 !important;">3</span></span> <span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">Urlcon.setreadtimeout (</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">30000</span></span><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 0, 0); line-height: 1.5 !important;">); </span></span></p></pre> <p><p><span style="font-size: 14px; color: rgb(57, 57, 57); line-height: 21px; font-family: verdana, ‘ms song‘, 微软雅黑, 宋体, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span></p></p> <p><p><br></p></p><p><p>The use of Android-class httpurlconnection</p></p></span>
Related Article

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.