Ways to send HTTP requests via Java.net.URLConnection

Source: Internet
Author: User

1. The difference between get and post requests

A) Get requests can get static pages, or they can be placed behind a URL string, passed to the servlet,

b) The difference between post and get is that the post parameter is not placed inside the URL string, but is placed inside the body of the HTTP request.

2. Objects of URLConnection

A) Get URLConnection instances

URL url = new URL (urlstring);//Generate URLConnection object based on URL URLConnection = (httpurlconnection) url.openconnection ();

b) Common parameter settings

//  set whether to export to httpurlconnection, because this is a POST request, the parameters to be placed in the  // http in the body, so it needs to be set to true,  by default False; httpurlconnection.setdooutput (True); //  Sets whether to read in from HttpURLConnection, True; httpurlconnection.setdoinput (True) by default; // post  requests cannot use the cache  httpurlconnection.setusecaches (False); //  sets the transferred content type to be serializable Java object  //  (if this item is not set, when the serialized object is transferred  httpurlconnection.setrequestproperty ("Content-type",  ") when the Web service defaults to not this type java.io.EOFException) Application/x-java-serialized-object "); //  the method for setting the request is" POST ", the default is get  Httpurlconnection.setrequestmethod ("POST");//Setting timeout (timeout), in the case of network anomalies, may cause the program to zombie without continuing to execute. System.setproperty ("sun.net.client.defaultConnectTimeout",  timeout number of milliseconds string); System.setproperty ("Sun.net.client.defaultReadTimeout",  time-out milliseconds string); 

  c)  httpurlconnection writing data and sending data problems

  Now constructs an object output stream object from the output stream object to implement the output serializable object.  outputstream outstrm = httpurlconnection.getoutputstream (); 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 byte to the potential stream (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 () function of the HttpURLConnection connection object, //  A complete HTTP request message encapsulated in the memory buffer is sent to the server.  inputstream instrm = httpconn.getinputstream ();  // <=== Note that the code snippet that actually sent 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//  both the object output stream does not call the close () method, The following operation does not write any data to the object output stream . //  Therefore, you need to re-create the connection, reset the parameters, recreate the stream object, re-write the data,  //  resend the data if you want to resend the data ( As to whether the operation needs to be re-examined)  objoutputstm.writeobject (new  String (""));  httpconn.getinputstream ();

3, code instance

Package org.zhangsm.httprequest;import java.io.bufferedreader;import java.io.ioexception;import  java.io.inputstream;import java.io.inputstreamreader;import java.net.httpurlconnection;import  java.net.URL;import java.util.Map;/** *  sends HTTP requests using Java Native APIs, which are Java.net.URL, Java.net.URLConnection. The  *  steps are as follows:  * 1, obtaining the connector  * 2 through the Uniform Resource Locator, setting the parameter of the request  * 3, retrieving the returned content as an input stream  *  4. Turn off input stream  *  @author  zhang.shuming * */public class HttpRequest {     public static void main (String[] args)  throws exception {         system.out.println (Send ("http://www.baidu.com",  "GET",  null, null));    }    private static string  Send (String urlstring,string method,    map<string,string> parameters , map< String,string> propertys)  throws Exception{             httpurlconnection urlconnection = null;    if ( Method.equalsignorecase ("GET")  && parameters != null) {Stringbuffer param  = new stringbuffer (); Int i = 0;for (string key :  Parameters.keyset ()) {if (i == 0)  param.append ("?"); Else param.append ("&");p Aram.append (key). Append ("="). Append (Parameters.get (key));i++;     }    urlstring += param;} Url url = new url (urlstring);//  generates URLConnection objects based on the URL urlconnection =  ( httpurlconnection)  url.openconnection ();//  Set Parameters Urlconnection.setrequestmethod (method); Urlconnection.setdooutput (True); Urlconnection.setdoinput (true); Urlconnection.setusecaches (false); if (propertys  != null) {for (string kEy : propertys.keyset ()) {Urlconnection.addrequestproperty (Key, propertys.get (key));}} if (Method.equalsignorecase ("POST")  && parameters != null) {Stringbuffer param  = new stringbuffer (); for (String key : parameters.keyset ()) {Param.append ("&" );p Aram.append (key). Append ("="). Append (Parameters.get (key));} Urlconnection.getoutputstream (). Write (Param.tostring (). GetBytes ()); Urlconnection.getoutputstream (). Flush (); Urlconnection.getoutputstream (). Close ();} Return makecontent (urlstring,urlconnection);} Private static string makecontent (string urlstring,httpurlconnection urlconnection)      throws IOException{InputStream in =  Urlconnection.getinputstream (); Bufferedreader bufferedreader = new bufferedreader (New inputstreamreader (in)); Stringbuffer temp = new stringbuffer (); String line;while ((line = bufferedreader.readline ())  != null) {temp.append (line);} Bufferedreader.close (); return temp.tostring ();}}

Ways to send HTTP requests via Java.net.URLConnection

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.