HttpURLConnection is basically a URLConnection of HTTP.

Uses of HttpURLConnection

It’s mainly used to send and receive data over the web. To make Http Requests.

Which data can be sent?

Well you can send any type of data over the web. From simple data types to complex data types like binary data.

That data may also be of any length.

You can even use HttpURLConnection to send and receive streams of data whose length is not know in advance.

Characteristics of HttpURLConnection

Let’s look at the programmatic nature of this very important class.

  1. First it belongs to package:
  2. It’s an abstract class:
    public abstract class HttpURLConnection..{}
  3. It derives from
    public abstract class HttpURLConnection extends URLConnection{}

HttpURLConnection children

This class has one child/subclass:

Class Description
HttpsURLConnection This is the HttpURLConnection for HTTPS.

How to work with HttpURLConnection

  1. HttpURLConnection instance is normally obtained by casting a URLConnection object to HttpURLConnection. That URLConnection is first of all obtained via a call to openConnection() method of the URL class.
  2. The above has given us a connection, so you need to prepare the request that you plan to make. Your request’s primary request is it’s URI. Your request headers may further contain metadata like session cookies, credentials etc.
  3. You can also send your request body. To do this you have to configure your HttpURLConnection by invoking the it’s setDoOutput(true), passing in true. You then send your data by writing it to a stream returned by getOutputStream().
  4. You can then read the returned response. The response headers can include metadata like body’s content type, length,sesssion cookies etc. The response body, you read from a stream. That stream you get by invoking the getInputStream().
  5. Lastly you disconnect from the connection once you’ve read the body. You do this by invoking the disconnect() method.This will free up the resources your connection was holding to.