javaandroidhttpurlconnection

Android: get data from internet via URL.getContent() - no need for HttpUrlConnection?


So far I've learned if I need to implement a method to retrieve data from an Internet server in an Android app, it's good to use HttpUrlConnection from Java as follows:

URL url = "http:\\www.stackoverflow.com/questions/json";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
     InputStream in = new BufferedInputStream(connection.getInputStream());
     readStream(in);
   } finally {
     connection.disconnect();
   }

But here on YouTube a man says not to retrieve a Bitmap simply by calling:

InputStream in = (InputStream) url.getContent();

I would like to point out that here we get Content from the url without calling HttpURLConnection.class and openConnection() method.

I followed that tutorial and the code compiles.

  1. Am I missing something, or isn't it necessary to use HttpURLConnection.class and openConnection()?
  2. If it's not necessary, why does Android documentation recommend using it?

Yes, I know, that besides HttpURLConnection it possible to use other packages (libraries), this question isn't about that. What I ask, is why I should use any type of connection if it's so simple to get data just calling URL.getContent()?


Solution

  • it's not necessary to use HttpURLConnection.class and getConnection() method?

    There is no getConnection() method. There is openConnection(). getContent() on an HTTP/HTTPS URL will use openConnection() as part of its processing, as is noted in the documentation for getContent() on URL.

    why Android documentation recommend me to use it?

    Nobody but the author of that documentation can tell you why they wrote that documentation. The author of that documentation is unlikely to respond to your question.

    Personally, I would recommend against the use of getContent() for several reasons:

    1. It is undocumented and not type-safe, meaning that the behavior could change on any device at the whim of the device manufacturer.

    2. HTTP error handling, with respect to getContent(), is also undocumented. What happens when the server returns a 404? A 401? A 500? A 301? A 304? Some of those you will need explicit handling for (e.g., retry with exponential backoff), which means you need to get at the response code. At minimum, you need to know whether the request succeeded and therefore whether the whatever-the-object-is that you get from getContent() will be valid. Your approach does not seem to offer much for this.

    3. Similarly, your approach ignores HTTP headers (request or response), such as those related to caching (Last-Modified, ETag, Expires).