Detailed description of URLConnection parameters in JDK (1)

Source: Internet
Author: User

For the issue of connecting Servlet with URLConnection in JDK, although there are some problems on the internet, it only illustrates one or several problems, which are solved by FAQ and scattered, now I will summarize the usage experience of this class in the project as follows:

1:> URL request category:

There are two types: GET and POST requests. The difference between the two is:

A: get requests can get static pages, or put parameters after URL strings and pass them to servlet,

B: The difference between post and get is that the post parameter is not placed in the URL string, but in the body of the http request.

2:> URLConnection objects:

The following code example shows the URLConnection object:

 
 
  1. // The following index. jsp is mapped
  2. // A Servlet (com. quantanetwork. getClientDataServlet)
  3. // Notes for this Servlet will be mentioned below
  4. URL url = new URL ("http: // localhost: 8080/TestHttpURLConnectionPro/index. jsp ");
  5.  
  6. URLConnection rulConnection = url. openConnection (); // The urlConnection object here is actually based on the URL
  7. // The URLConnection class generated by the request protocol (http)
  8. // Subclass HttpURLConnection, so it is best to convert it
  9. // An object of the HttpURLConnection type for use
  10. // More HttpURLConnection APIs are as follows:
  11.  
  12. HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection;

3:> HttpURLConnection object parameters

 
 
  1. // Set whether to output data to httpUrlConnection. Because this is a post request, the parameter must be placed in
  2. // Set it to true in the http body. The default value is false;
  3. HttpUrlConnection. setDoOutput (true );
  4.  
  5. // Set whether to read data from httpUrlConnection. The default value is true;
  6. HttpUrlConnection. setDoInput (true );
  7.  
  8. // The Post request cannot use the cache.
  9. HttpUrlConnection. setUseCaches (false );
  10.  
  11. // Set the transmitted content type to a serializable java object.
  12. // (If this option is not set, java. io. EOFException may be thrown when the WEB service is not of this type by default when the serialized object is transmitted)
  13. HttpUrlConnection. setRequestProperty ("Content-type", "application/x-java-serialized-object ");
  14.  
  15. // Set the request method to "POST". The default value is GET.
  16. HttpUrlConnection. setRequestMethod ("POST ");
  17.  
  18. // Connection. The url. openConnection () configuration must be completed before connect from the above 2nd entries,
  19. HttpUrlConnection. connect ();

4:> HttpURLConnection connection:

 
 
  1. // GetOutputStream implicitly performs connect (that is, it calls the above connect () method,
  2. // You can do this without calling the above connect () during development ).
  3. OutputStream outStrm = httpUrlConnection. getOutputStream ();

5:> HttpURLConnection:

 
 
  1. // Now, an object output stream object is built through the output stream object to achieve output serializable objects.
  2. ObjectOutputStream objOutputStrm = new ObjectOutputStream (outStrm );
  3.  
  4. // Write data to the output stream of the object. The data will be stored in the memory buffer.
  5. ObjOutputStrm. writeObject (new String ("I'm Test Data "));
  6.  
  7. // Refresh the object output stream and write any byte into some potential streams as ObjectOutputStream)
  8. ObjOutputStm. flush ();
  9.  
  10. // Close the stream object. At this time, no data can be written to the object output stream. previously written data exists in the memory buffer,
  11. // Send the prepared http request to the server only when the getInputStream () function is called.
  12. ObjOutputStm. close ();
  13.  
  14. // Call the getInputStream () function of the HttpURLConnection connection object,
  15. // Send the complete HTTP Request Message encapsulated in the memory buffer to the server.
  16. InputStream merge M = httpConn. getInputStream (); // <= Note: The actual code segment for sending the request is here
  17.  
  18. // The above httpConn. getInputStream () method has been called. This HTTP request has ended and the output of the following output stream to the object is meaningless,
  19. // Even if the object output stream does not call the close () method, the following operation will not write any data to the object output stream.
  20. // Therefore, to re-send data, you need to re-create the connection, reset parameters, re-create a stream object, re-write data,
  21. // Resend the data (you need to study whether to re-send the data)
  22. ObjOutputStm. writeObject (new String (""));
  23. HttpConn. getInputStream ();

Summary:

A: The connect () function of HttpURLConnection actually only establishes a tcp connection with the server and does not actually send an http request.

Whether it is post or get, the http request is not officially sent until the getInputStream () function of HttpURLConnection.

B: When using POST to send a URL request, the Setting Order of URL request parameters is the top priority. All the configuration of the connection object must be performed in connect () function execution is completed. The write operation on outputStream must be performed before the read operation on inputStream.

These sequences are actually determined by the format of the http request.

If the read operation of inputStream is performed before the write operation of outputStream, an exception is thrown:

 
 
  1. java.net.ProtocolException: Cannot write output after reading input....... 

C: The http request is actually composed of two parts: one is the http header, and all configurations about this http request are defined in the http header, and the other is the body content.

The connect () function generates http header information based on the configuration value of the HttpURLConnection object. Therefore, you must prepare all the configurations before calling the connect function.

D: The http header is followed by the http Request body. The body content is written through the outputStream stream. In fact, outputStream is not a network stream, but a string stream at best, the content written into the file is not immediately sent to the network, but exists in the memory buffer. When the outputStream stream is closed, the http body is generated based on the input content. Now, all http request items are 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 response to this http request. Because the http request has sent an http header and body when getInputStream is used), the connection object is set after the getInputStream () function to modify the http header information) or write outputStream to modify the body) is meaningless, the execution of these operations will cause exceptions.


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.