Android HttpURLConnection suggest change

Creating an HttpURLConnection

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();
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents