Java calls HTTP request-httpurlconnection Learning

Source: Internet
Author: User

The most commonly used HTTP request is nothing more than get and post,get requests can get static pages, you can also put the parameters behind the URL string, passed to Servlet,post and get the difference is that the post parameters are not placed in the URL string inside, Instead, it is placed inside the body of the HTTP request.
You can use HttpURLConnection to initiate both of these requests in Java, which is helpful for understanding soap and writing automated test code for Servlets.
The following code briefly describes how to use HttpURLConnection to initiate both requests, and the method of passing parameters:

 Public classHttpinvoker { Public Static FinalString Get_url = "Http://localhost:8080/welcome1";  Public Static FinalString post_url = "Http://localhost:8080/welcome1";  Public Static voidReadcontentfromget ()throwsIOException {//Patchwork URL strings for Get requests, using Urlencoder.encode to encode special and invisible charactersString GetURL = Get_url + "? Username=" + Urlencoder.encode ("Fat Man", "Utf-8"); URL GETURL=NewURL (GetURL); //depending on the URL, the Url.openconnection function will open the connection, depending on the type of URL,//returns an object of different urlconnection subclasses, where the URL is an HTTP, so the actual return is HttpURLConnectionHttpURLConnection connection =(HttpURLConnection) getUrl. OpenConnection (); //, but actually the GET request will be sent to the Connection.getinputstream () function in the next sentence.//ServerConnection.connect (); //get the input stream and read it using readerBufferedReader reader =NewBufferedReader (NewInputStreamReader (Connection.getinputstream ())); System.out.println ("============================="); System.out.println ("Contents of Get Request"); System.out.println ("=============================");        String lines;  while((lines = Reader.readline ())! =NULL) {System.out.println (lines);        } reader.close (); //Disconnect ConnectionConnection.disconnect (); System.out.println ("============================="); System.out.println ("Contents of Get Request Ends"); System.out.println ("============================="); }     Public Static voidReadcontentfrompost ()throwsIOException {//the URL of the POST request, unlike get, is not required with parametersURL PostURL =NewURL (Post_url); //Open ConnectionHttpURLConnection connection =(HttpURLConnection) posturl. OpenConnection (); //Output to the connection. Default is//false, set to True because post//method must write something to the//Connection//set whether to output to connection, because this is a POST request, the parameters to be placed in the//http in the body, so it needs to be set to trueConnection.setdooutput (true); //Read from the connection. Default is true.Connection.setdoinput (true); //Set The Post method. Default is GETConnection.setrequestmethod ("POST"); //Post cannot use caches//The Post request cannot use the cacheConnection.setusecaches (false); //This method takes effects to//every instances of this class. //urlconnection.setfollowredirects is a static function that is used for all URLConnection objects. //connection.setfollowredirects (TRUE); //This methods only//takes effacts to this//instance. //Urlconnection.setinstancefollowredirects is a member function and is used only for the current functionConnection.setinstancefollowredirects (true); //Set The content type to urlencoded,//because we'll write//some url-encoded content to the//connection.        Settings above must be set before connect! //Configure the Content-type of this connection, configured as application/x-www-form-urlencoded//This means that the text is urlencoded encoded form parameter, below we can see we use Urlencoder.encode for body content//to encodeConnection.setrequestproperty ("Content-type",                "Application/x-www-form-urlencoded"); //connection, from Posturl.openconnection () to this point the configuration must be done before connect,//It is important to note that Connection.getoutputstream will implicitly connect. Connection.connect (); DataOutputStream out=NewDataOutputStream (connection. Getoutputstream ()); //The url-encoded contend//text, body content actually with get URL in '? ' After the argument string is consistentString content = "Firstname=" + urlencoder.encode ("A Big Fat Man", "Utf-8"); //Dataoutputstream.writebytes writes a 16-bit Unicode character in a string as a 8-bit character in the streamout.writebytes (content);        Out.flush (); Out.close (); //Flush and closeBufferedReader reader =NewBufferedReader (NewInputStreamReader (Connection.getinputstream ()));        String Line; System.out.println ("============================="); System.out.println ("Contents of Post request"); System.out.println ("=============================");  while(line = Reader.readline ())! =NULL) {System.out.println (line); } System.out.println ("============================="); System.out.println ("Contents of Post request Ends"); System.out.println ("=============================");        Reader.close ();    Connection.disconnect (); }    /** *//**     * @paramargs*/     Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        Try{readcontentfromget ();        Readcontentfrompost (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}

Above theThe Readcontentfromget () function produces a GET request that is passed to the servlet with a username parameter with the value "Fat Man".
The Readcontentfrompost () function produces a POST request to the servlet with a FirstName parameter, which is a value of "a Big Fat Man".
The Httpurlconnection.connect function, in effect, simply establishes a TCP connection to the server and does not actually send an HTTP request. Either the post or the get,http request actually untilHttpURLConnectionThe. getInputStream () function is only formally sent out.

InIn Readcontentfrompost (), the order is the most important, and all configuration of the connection object (that heap of set functions) must be done before the Connect () function executes. The write operation to OutputStream must be preceded by the InputStream read operation. These orders are actually determined by the format of the HTTP request.

The HTTP request actually consists of two parts, one is the HTTP header, and all the configuration about this HTTP request is defined in the HTTP header, one is the body content, in the Connect () function, HTTP headers are generated based on the configuration values of the HttpURLConnection object, so all configurations must be ready before calling the Connect function.

Immediately after the HTTP header is the body of the HTTP request, the content of the body is written by outputstream, in fact, OutputStream is not a network stream, at best, is a string stream, what is written to it will not be sent to the network immediately, but after the stream is closed, Generates an HTTP body based on what you enter.

At this point, the HTTP request is ready. When the getInputStream () function is called, the prepared HTTP request is formally sent to the server, and an input stream is returned to read the server's return information for this HTTP request. Since the HTTP request was sent out at getInputStream (including the HTTP header and the body), the connection object was set after the getInputStream () function (the information for the HTTP header was modified) or written OutputStream (Modifying the body) is meaningless, and performing these operations can cause an exception to occur.
The last section says that the outputstream of a POST request is actually not a network stream, but rather a write memory, in which the contents of the stream inside the getInputStream are really merged into a real HTTP request header based on the previous configuration. Request, and then actually send it to the server at this time.

The Httpurlconnection.setchunkedstreamingmode function can change this pattern, set the Chunkedstreamingmode, and no longer wait for the outputstream to close and generate the full HTTP The request sends the HTTP request header first, and the body content is transmitted to the server in real time by means of a network stream. In fact, it does not tell the length of the HTTP body of the server, which is suitable for transmitting to the server large or not easily accessible lengths of data, such as files.

 Public Static voidReadcontentfromchunkedpost ()throwsIOException {URL PostURL=NewURL (Post_url); HttpURLConnection Connection=(HttpURLConnection) posturl. OpenConnection (); Connection.setdooutput (true); Connection.setdoinput (true); Connection.setrequestmethod ("POST"); Connection.setusecaches (false); Connection.setinstancefollowredirects (true); Connection.setrequestproperty ("Content-type",                "Application/x-www-form-urlencoded"); /**//* * differs from readcontentfrompost () by setting a block size of 5 bytes*/Connection.setchunkedstreamingmode (5);        Connection.connect (); /**//* * Note that the following Getoutputstream function works in the same way as in Readcontentfrompost () * Inside the readcontentfrompost () The function is still preparing the HTTP re Quest, no data is sent to the server * and here, because the Chunkedstreamingmode,getoutputstream function is set to generate an HTTP request header based on the configuration * before connect, it is first sent to         Server. */DataOutputStream out=NewDataOutputStream (connection. Getoutputstream ()); String content= "Firstname=" + urlencoder.encode ("A Big Fat Man") + "" + "Asdfasfdasfasdfaasdfasdfasdfdasfs", "Utf-8 ");         Out.writebytes (content);        Out.flush (); Out.close (); //At this point the server has received the full HTTP request, and in the Readcontentfrompost () function, wait for the next server to receive HTTP requests. BufferedReader reader =NewBufferedReader (NewInputStreamReader (Connection.getinputstream ()));        Out.flush (); Out.close (); //Flush and closeString Line; System.out.println ("============================="); System.out.println ("Contents of Post request"); System.out.println ("=============================");  while(line = Reader.readline ())! =NULL) {System.out.println (line); } System.out.println ("============================="); System.out.println ("Contents of Post request Ends"); System.out.println ("=============================");        Reader.close ();    Connection.disconnect (); }

Java calls HTTP request-httpurlconnection Learning

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.