Java Reference
In-Depth Information
C
HAPTER
4: B
EYOND
S
IMPLE
R
EQUESTS
• The HttpURLConnection Class
• Reading HTTP Response Headers
• Setting HTTP Request Headers
• Managing HTTP Timeouts
The connection between a bot and a web server is very important. In the previous chap-
ters this link was established using either a
Socket
object or an
InputStream
object,
obtained from a call to the
openStream
function of a
URL
class. There is a third way to
open a connection to a web server—you can use the
HttpURLConnection
object. In
summary, the three ways to open a connection to a web server are:
•
Socket
•
InputStream
from
URL.openStream
•
HttpURLConnection
The
HttpURLConnection
class allows much more flexibility than just using an
InputStream
object. It is also much simpler to use than a socket.
Introducing HttpURLConnection
The
HttpURLConnection
class provides many additional options that you do not
have access to with only an
InputStream
. The
HttpURLConnection
class pro-
vides access to the following operations:
• Reading data from the URL
• Posting data to the URL
• Setting client headers
• Reading server headers
• Setting socket parameters
Using the
HttpURLConnection
class is easy enough. It is created us-
ing a
URL
object, much like the
InputStream
. The following code creates an
HttpURLConnection
class:
URL u = new URL("http://www.httprecipes.com");
HttpURLConnection http = (HttpURLConnection)u.openConnection();
Once you have the
HttpURLConnection
object, you can easily get an
InputStream
to the web site. This will allow you to download the contents of the web
site, just as you did in Chapter 3, “Simple HTTP Requests”. The following line of code obtains
an
InputStream
from the
HttpURLConnection
object created above.
InputStream is = http.getInputStream();