Android:通过URL.getContent()从互联网获取数据 - 不需要HttpUrlConnection?

时间:2017-01-08 14:44:20

标签: java android httpurlconnection

到目前为止,我已经了解到我是否需要实现方法从Android应用程序中的Internet服务器检索数据,最好使用Java中的HttpUrlConnection,如下所示:

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

但是这里YouTube一个人只是通过调用:

来讲述热点来检索一个Bitmap
InputStream in = (InputStream) url.getContent();

我想指出,在这里我们从url获取内容而不调用HttpURLConnection.class和openConnection()方法。

我按照该教程编写代码。
1)我是否遗漏了某些东西,或者没有必要使用HttpURLConnection.class和openConnection()方法?
2)如果没有必要,为什么Android文档会建议我使用它?

是的,我知道,除了HttpURLConnection之外,还可以使用其他软件包(库),这个问题与此无关。我问,为什么我应该使用任何类型的连接,如果只是调用URL.getContent()来获取数据这么简单?

2 个答案:

答案 0 :(得分:1)

  

没有必要使用HttpURLConnection.class和getConnection()方法?

没有getConnection()方法。有openConnection()。 HTTP / HTTPS网址上的getContent()将使用openConnection()作为其处理的一部分,如the documentation for getContent() on URL中所述。

  

为什么Android文档会建议我使用它?

除了该文档的作者之外,没有人可以告诉你他们为什么要编写该文档。该文档的作者不太可能回答您的问题。

就个人而言,我建议不要使用getContent(),原因如下:

  1. 它没有文档记录,也不是类型安全的,这意味着设备制造商可能随时随地改变行为。

  2. 关于getContent()的HTTP错误处理也没有记录。当服务器返回404时会发生什么?一个401?一个500?一个301?一个304?其中一些您需要明确处理(例如,使用指数退避重试),这意味着您需要获取响应代码。至少,您需要知道请求是否成功,因此您从getContent()获得的对象是否有效。你的方法似乎没有为此提供太多。

  3. 同样,您的方法会忽略HTTP标头(请求或响应),例如与缓存(Last-ModifiedETagExpires)相关的标头。

    < / LI>

答案 1 :(得分:0)

Sure he used HttpURLConnection, but instead of connection.getInputStream() he used connection.getContent() which retruns an Object instance.

As of the documentation; getContent() already uses getInputStream() internally to retrieve the content and getContentType() to load the proper class (such as JSON).

I recommend you to use getInputStream() because it allows you to handle errors, different types of response codes and to decide which class to use with this data type.

also URL has a method called getContent() whitch is a shorthand for: connection.getContnet();