Introducing HttpURLConnection | Heaton Research

Introducing HttpURLConnection

    The HttpURLConnection class provides many additional options that you do not have access to with only an InputStream. The HttpURLConnection class provides 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 using 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();

    In addition to the InputStream, each HttpURLConnection object also has an OutputStream, if requested. The following code requests an OutputStream for the HttpURLConnection object.

OutputStream os = http.getOutputStream();

    If you use the OutputStream to send data to the web server, then the HTTP request will be a POST request. If you do not make use of the OutputStream, the request will be a GET. POST requests are usually used when the user responds to a form. Chapter 7, “Responding to Forms,” will show you how to use forms and POST requests.

Copyright 2005-2009 by Heaton Research, Inc.