Android HttpURLConnection Creating an HttpURLConnection

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

In order to create a new Android HTTP Client HttpURLConnection, call openConnection() on a URL instance. Since openConnection() returns a URLConnection, you need to explicitly cast the returned value.

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// do something with the connection

If you are creating a new URL, you also have to handle the exceptions associated with URL parsing.

try {
    URL url = new URL("http://example.com");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    // do something with the connection
} catch (MalformedURLException e) {
    e.printStackTrace();
}

Once the response body has been read and the connection is no longer required, the connection should be closed by calling disconnect().

Here is an example:

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
    // do something with the connection
} finally {
    connection.disconnect();
}


Got any Android Question?