Detailed description of urlconnection parameters in JDK

Source: Internet
Author: User
Detailed description of urlconnection parameters in JDK

From: http://www.blogjava.net/supercrsky/articles/247449.html

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:

// The following index. jsp is mapped
// A servlet (COM. quantanetwork. getclientdataservlet)
// Notes for this servlet will be mentioned below
URL url = new URL ("http: // localhost: 8080/testhttpurlconnectionpro/index. jsp ");

Urlconnection rulconnection = URL. openconnection (); // The urlconnection object here is actually based on the URL
// The urlconnection class generated by the request protocol (HTTP)
// Subclass httpurlconnection, so it is best to convert it
// An object of the httpurlconnection type for use
// More httpurlconnection APIs are as follows:

Httpurlconnection = (httpurlconnection) rulconnection;

3:> httpurlconnection object parameters
// Set whether to output data to httpurlconnection. Because this is a POST request, the parameter must be placed in
// Set it to true in the HTTP body. The default value is false;
Httpurlconnection. setdooutput (true );

// Set whether to read data from httpurlconnection. The default value is true;
Httpurlconnection. setdoinput (true );

// The POST request cannot use the cache.
Httpurlconnection. setusecaches (false );

// Set the transmitted content type to a serializable Java object.
// (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)
Httpurlconnection. setrequestproperty ("Content-Type", "application/X-Java-serialized-object ");

// Set the request method to "Post". The default value is get.
Httpurlconnection. setrequestmethod ("Post ");

// Connection. The URL. openconnection () configuration must be completed before connect from the above 2nd entries,
Httpurlconnection. Connect ();

4:> httpurlconnection connection:

// Getoutputstream implicitly performs connect (that is, it calls the above connect () method,
// You can do this without calling the above connect () during development ).
Outputstream outstrm = httpurlconnection. getoutputstream ();


5:> httpurlconnection:
// Now, an object output stream object is built through the output stream object to achieve output serializable objects.
Objectoutputstream objoutputstrm = new objectoutputstream (outstrm );

// Write data to the output stream of the object. The data will be stored in the memory buffer.
Objoutputstrm. writeobject (new string ("I'm Test Data "));

// Refresh the object output stream and write any byte into the potential stream (some are objectoutputstream)
Objoutputstm. Flush ();

// 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,
// Send the prepared HTTP request to the server only when the getinputstream () function is called.
Objoutputstm. Close ();

// Call the getinputstream () function of the httpurlconnection connection object,
// Send the complete HTTP Request Message encapsulated in the memory buffer to the server.
Inputstream merge M = httpconn. getinputstream (); // <= Note: The actual code segment for sending the request is here

// 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,
// 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.
// Therefore, to re-send data, you need to re-create the connection, reset parameters, re-create a stream object, re-write data,
// Resend the data (you need to study whether to re-send the data)
Objoutputstm. writeobject (new string (""));
Httpconn. getinputstream ();


Conclusion: A: The CONNECT () function of httpurlconnection actually only establishes a TCP connection with the server and does not actually send HTTP requests.
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, setting the order of URL request parameters is a top priority,
Configure everything for the connection object (that pile of set functions)
All must be completed before the connect () function is executed. 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:
Java.net. protocolexception: cannot write output after reading input .......

C: The HTTP request is actually composed of two parts,
One is the HTTP header. All configurations for this HTTP request are defined in the HTTP header,
One is body content.
The CONNECT () function generates HTTP header information based on the configuration value of the httpurlconnection object. Therefore, before calling the connect function,
All configurations must be ready.
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. At best, it is a string stream. What is written into it is not immediately sent to the network,
It exists in the memory buffer. When the outputstream stream is disabled, 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
It is officially sent to the server, and an input stream is returned to read the server's returned information for this HTTP request. Because HTTP
The request has been sent when getinputstream (including the HTTP header and body), so the getinputstream () function
Then set the connection object (modify the HTTP header information) or write outputstream (modify the body)
All of them are meaningless. executing these operations will lead to exceptions.

6:> Notes for servlet development:
A: For post-Type HTTP requests sent by the client, the servlet must implement the dopost method instead of the doget method.
B: Use the getinputstream () method of httpservletrequest to retrieve the inputstream object, for example:
Inputstream instream = httprequest. getinputstream ();
Now call instream. Available () (this method is used to "return the next method call of this input stream can be non-congested
When the input stream reads (or skips) the estimated number of bytes ", the return value is always 0. Try to use the return value of this method to allocate a buffer,
It is incorrect to save all the data in this stream. The solution is
The servlet end is implemented as follows:
Inputstream instream = httprequest. getinputstream ();
Objectinputstream objinstream = new objectinputstream (instream );
Object OBJ = objinstream. readobject ();
// Perform subsequent processing
//......
//... ...
The client writes an object regardless of whether the actual data is sent (for fear that this object is not used), such:
Objectoutputstream objoutputstrm = new objectoutputstream (outstrm );
Objoutputstrm. writeobject (new string (""); // an empty data is sent here.
// You can even send a null object, which is obtained by the server and then processed.
Objoutputstrm. writeobject (null );
Objoutputstrm. Flush ();
Objoutputstrm. Close ();

Note: When you create an object output stream objectoutputstream, if the input stream obtained from httpservletrequest
(That is, the outstrm in new objectoutputstream (outstrm) is packaged in the bufferedoutputstream stream,
The objoutputstrm. Flush (); statement must be provided to fl the stream information into the buffer output stream:
Objectoutputstream objoutputstrm = new objectoutputstream (New bufferedoutputstream (outstrm ));
Objoutputstrm. writeobject (null );
Objoutputstrm. Flush (); // <====== required.
Objoutputstrm. Close ();



Httpurlconnection is based on the HTTP protocol and is implemented through socket communication at the underlying layer. If the timeout value is not set, the program may be frozen and will not continue to be executed due to network exceptions. You can use the following two statements to set the corresponding Timeout:
System. setproperty ("sun.net. Client. defaulttimetimeout", timeout string in milliseconds );
System. setproperty ("sun.net. Client. defaultreadtimeout", timeout string in milliseconds );

Among them: sun.net. Client. defaultconnecttimeout: the timeout time for connecting to the host (unit: milliseconds)
Sun.net. Client. defaultreadtimeout: the timeout time for reading data from the host (unit: milliseconds)

For example:
System. setproperty ("sun.net. Client. defaulttimetimeout", "30000 ");
System. setproperty ("sun.net. Client. defaultreadtime

In Java, httpurlconnection can be used to request web resources.
The httpurlconnection object cannot be constructed directly. You need to use URL. openconnection () to obtain the httpurlconnection object. The sample code is as follows:

String szurl = "http://www.ee2ee.com /";
URL url = new URL (szurl );
Httpurlconnection urlcon = (httpurlconnection) URL. openconnection ();

 

Httpurlconnection is based on the HTTP protocol and is implemented through socket communication at the underlying layer. If the timeout value is not set, the program may be frozen and will not continue to be executed due to network exceptions. You can use the following two statements to set the corresponding Timeout:
System. setproperty ("sun.net. Client. defaulttimetimeout", timeout string in milliseconds );
System. setproperty ("sun.net. Client. defaultreadtimeout", timeout string in milliseconds );

Among them: sun.net. Client. defaultconnecttimeout: the timeout time for connecting to the host (unit: milliseconds)
Sun.net. Client. defaultreadtimeout: the timeout time for reading data from the host (unit: milliseconds)

For example:
System. setproperty ("sun.net. Client. defaulttimetimeout", "30000 ");
System. setproperty ("sun.net. Client. defaultreadtimeout", "30000 ");

In versions earlier than JDK 1.5, only the two system attributes can be set to control network timeout. In 1.5, you can also use the following two methods of the httpurlconnection parent class urlconnection:
Setconnecttimeout: sets the host connection timeout (unit: milliseconds)
Setreadtimeout: sets the time-out for data reading from the host (unit: milliseconds)

For example:

Httpurlconnection urlcon = (httpurlconnection) URL. openconnection ();
Urlcon. setconnecttimeout (30000 );
Urlcon. setreadtimeout (30000 );

 

Note that, in the jdk1.4.2 environment, I found that when defaultreadtimeout is set, if the network times out, httpurlconnection will automatically submit a request again, and a request call will appear, trouble ). I think this is a bug in jdk1.4.2. In jdk1.5.0, this problem has been solved and automatic resend does not exist. Out "," 30000 ");

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.