Java Reference
In-Depth Information
Calling Sequence
As you have seen in this chapter, there is a variety of operations that can be performed on
an HttpURLConnection object. You can set request headers, read response headers,
POST data and read response data. Please note, however, that there is a very specific order
that these operations must follow. For example, you can't set a request header, after you are
already reading the response. If you are reading the web server's reply, the request was al-
ready sent. Therefore, all request information must be set before you begin working with the
response. The general order that you should follow is shown here:
• Step 1: Set any HTTP request headers.
• Step 2: POST data, if this is a POST request.
• Step 3: Read HTTP response headers.
• Step 4: Read HTTP response data.
If you ever face a bug where it seems the request headers are being ignored, check to
see if you are not already calling a method related to the response before setting the header.
All headers must be set before the request is sent.
Other Useful Options
In addition to headers, there are other useful options that the HttpURLConnection
class provides. Although there are a number of options in the HttpURLConnection
class that are used only for very rare or obscure situations, in this section we will examine
the two most common options used in the HttpURLConnection class. The two most
frequently used are “timeouts” and “redirect following”. The next two sections will cover
these options.
Timeout
When you request that the HttpURLConnection class process a URL, certain
operations can timeout. The HttpURLConnection class will wait a certain amount of
milliseconds, before it times out. There is a default value of time; however, you can adjust this
time to be longer or shorter to suit your needs. There are two different timeouts supported
by Java:
• Timeout while connecting to the web host.
• Timeout while transferring data with the web host.
To control the timeout value while connecting to the host, you should use the
setConnectionTimeout on the HttpURLConnection class. Likewise, you
can call the getConnectionTimeout to determine the current connection timeout.
The timeout is measured in milliseconds. For instance, to set the connection timeout to one
second you would use the following line of code:
http.setConnectionTimeout(1000);
Search WWH ::




Custom Search