Creating an HttpURLConnection
suggest changeIn 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();
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents