URLConnection parameters in the JDK

Source: Internet
Author: User

For the JDK in the URLConnection connection servlet problem, although the Internet has been involved, but only to explain a certain or a few problems, is the way to solve the FAQ, and relatively fragmented, now on the use of this class I in the project experience to do the following summary:
1:> the category of the URL request:
Divided into two categories, get and post requests. The difference between the two is:
A:) Get request can get a static page, or you can put the parameters behind the 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:> URLConnection Object problem:
URLConnection object, the following code example:

The following index.jsp is mapped from <servlet-mapping> to
A servlet (Com.quantanetwork.getClientDataServlet)
The servlet's attention points are mentioned below
URL url =NewURL ("http://localhost:8080/TestHttpURLConnectionPro/index.jsp");

URLConnection rulconnection = Url.openconnection ();// the URLConnection object here is actually based on the URL's
// the URLConnection class that the request protocol (here is HTTP) generates
// sub-class httpurlconnection, so it is best to convert it
// is an object of type httpurlconnection for use with the
// httpurlconnection more APIs. The following:

HttpURLConnection httpurlconnection = (httpurlconnection) rulconnection;

3:> HttpURLConnection Object parameter problems
// set whether to output 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, false by default;
Httpurlconnection.setdooutput (true);

// sets whether to read in from HttpURLConnection, true by default;
Httpurlconnection.setdoinput (true);

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

// sets the content type of the transfer to be a serializable Java object
// (if this item is not set, the java.io.EOFException may be thrown when the serialized object is passed, when the Web service defaults to this type)
Httpurlconnection.setrequestproperty ("Content-type", "Application/x-java-serialized-object");

// The method for setting the request is "POST", and the default is get
Httpurlconnection.setrequestmethod ("POST");

// connection, from the 2nd above url.openconnection () the configuration must be completed before connect,
Httpurlconnection.connect ();

4:> HttpURLConnection Connectivity Issues:

// here Getoutputstream will implicitly connect (that is, like calling the Connect () method above,
// so it is not possible to call the above connect () in development.
OutputStream OUTSTRM = Httpurlconnection.getoutputstream ();


5:> httpurlconnection Write data and send data problems:
// The object output stream object is now built from the output stream object to implement the output serializable object.
ObjectOutputStream OBJOUTPUTSTRM =NewObjectOutputStream (OUTSTRM);

// writes out the data to the object output stream, which is stored in the memory buffer
Objoutputstrm.writeobject (NewString ("I am the test Data"));

// refreshes the object output stream and writes any bytes to the potential stream (ObjectOutputStream)
Objoutputstm.flush ();

// closes the Stream object. At this point, no data can be written to the object output stream, and 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 ();

// Call 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.
// 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, you need to re-create 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 (NewString (""));
Httpconn.getinputstream ();


Summary: A:) The Connect () function of httpurlconnection actually only establishes a TCP connection to the server and does not actually send an HTTP request.
Either the post or the Get,http request is actually sent out until the httpurlconnection getInputStream () function.
B:) When sending a URL request by post, the URL request parameters are set in the order of the most heavy,
All configuration of the connection object (that heap of set functions)
Must be completed 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.
If the InputStream read operation precedes the write operation of OutputStream, an exception is thrown:
Java.net.ProtocolException:Cannot write output after reading input ....

C:) 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 text content.
The Connect () function generates HTTP header information based on the configuration values of the HttpURLConnection object, so before calling the Connect function, the
You have to get all the configurations ready.
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,
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,
Instead, it exists in the memory buffer, and the HTTP body is generated based on what is entered when the OutputStream stream is closed.
At this point, the HTTP request is ready for everything. When the getInputStream () function is called, the prepared HTTP request is
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
The request was sent out at getInputStream (including the HTTP header and body), so the getInputStream () function
The connection object is then set (modification of the HTTP header information) or written to OutputStream (the body is modified)
is meaningless, performing these operations can cause an exception to occur.

6:> servlet Side Development Note:
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.
B:) Use the HttpServletRequest getInputStream () method to obtain InputStream objects, such as:
InputStream instream = Httprequest.getinputstream ();
Now call Instream.available () (the method used to "return this input to the stream" where a method call can be unblocked
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.
It is incorrect to save all the data in this stream. So, the solution now is
This end of the servlet is implemented as follows:
InputStream instream = Httprequest.getinputstream ();
ObjectInputStream objinstream = new ObjectInputStream (instream);
Object obj = Objinstream.readobject ();
Do the follow-up processing
。。。。。。
。。。 。。。
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:
ObjectOutputStream OBJOUTPUTSTRM = new ObjectOutputStream (OUTSTRM);
Objoutputstrm.writeobject (New String ("")); Send an empty data here
You can even send a null object, and the service end is taken and then processed.
Objoutputstrm.writeobject (NULL);
Objoutputstrm.flush ();
Objoutputstrm.close ();

Note: When you create an object output stream ObjectOutputStream, the input stream that is taken from HttpServletRequest
(i.e., OUTSTRM in new ObjectOutputStream (OUTSTRM) is wrapped in a bufferedoutputstream flow,
Must have Objoutputstrm.flush (); This sentence, in order to brush the flow information into the buffered output stream.
ObjectOutputStream OBJOUTPUTSTRM = new ObjectOutputStream (new Bufferedoutputstream (OUTSTRM));
Objoutputstrm.writeobject (NULL);
Objoutputstrm.flush (); <====== must have it here.
Objoutputstrm.close ();



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:
System.setproperty ("Sun.net.client.defaultConnectTimeout", time-out number of milliseconds string);
System.setproperty ("Sun.net.client.defaultReadTimeout", time-out number of milliseconds string);

Where: Sun.net.client.defaultConnectTimeout: Time-out for connecting the host (in milliseconds)
Sun.net.client.defaultReadTimeout: timeout (in milliseconds) to read data from the host

For example:
System.setproperty ("Sun.net.client.defaultConnectTimeout", "30000");
System.setproperty ("Sun.net.client.defaultReadTime

in Java, you can use HttpURLConnection to request Web resources.
The HttpURLConnection object cannot be constructed directly and needs to be url.openconnection () to obtain the HttpURLConnection object, as shown in the example code:

String szurl = "http://www.ee2ee.com/";
URL url =NewURL (Szurl);
HttpURLConnection Urlcon = (httpurlconnection) url.openconnection ();

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:
System.setproperty ("Sun.net.client.defaultConnectTimeout", time-out number of milliseconds string);
System.setproperty ("Sun.net.client.defaultReadTimeout", time-out number of milliseconds string);

Where: Sun.net.client.defaultConnectTimeout: Time-out for connecting the host (in milliseconds)
Sun.net.client.defaultReadTimeout: timeout (in milliseconds) to read data from the host

For example:
System.setproperty ("Sun.net.client.defaultConnectTimeout", "30000");
System.setproperty ("Sun.net.client.defaultReadTimeout", "30000");

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:
Setconnecttimeout: Setting the connection host timeout (in milliseconds)
Setreadtimeout: Setting read data timeout from host (in milliseconds)

For example:

HttpURLConnection Urlcon = (httpurlconnection) url.openconnection ();
Urlcon.setconnecttimeout (30000);
Urlcon.setreadtimeout (30000);

It is important to note that The author in the JDK1.4.2 environment, found that in the case of setting up Defaultreadtimeout, if a network timeout occurs, HttpURLConnection will automatically resubmit the request, a request call, the request server two times the problem (trouble). I think this is a bug in JDK1.4.2. In JDK1.5.0, this issue has been resolved and there is no automatic re-occurrence. Out "," 30000 ");

URLConnection parameters in the JDK

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.