4

读取 HttpURLConnection 的 InputStream 时,是否有理由使用以下其中之一?我已经在示例中看到了两者。

手动缓冲:

while ((length = inputStream.read(buffer)) > 0) {
    os.write(buf, 0, ret);
}

缓冲输入流

is = http.getInputStream();
bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);

int current = 0;
while ((current = bis.read()) != -1) {
     baf.append(current);
}

编辑一般来说,我对 HTTP 还是很陌生,但我想到的一个考虑是,如果我使用的是持久 HTTP 连接,我不能在输入流为空之前读取,对吗?在那种情况下,我不需要读取消息长度并只读取该长度的输入流吗?

同样,如果不使用持久连接,我包含的代码在正确读取流方面是否 100% 好?

4

4 回答 4

5

我在我的博客上一篇关于在 android 中使用 JSON 的文章中谈到了一个很好的方法。http://blog.andrewpearson.org/2010/07/android-why-to-use-json-and-how-to-use.html。我将在下面发布相关帖子的相关部分(代码非常通用):

InputStream in = null;
String queryResult = "";
try {
     URL url = new URL(archiveQuery);
     HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
     HttpURLConnection httpConn = (HttpURLConnection) urlConn;
     httpConn.setAllowUserInteraction(false);
     httpConn.connect();
     in = httpConn.getInputStream();
     BufferedInputStream bis = new BufferedInputStream(in);
     ByteArrayBuffer baf = new ByteArrayBuffer(50);
     int read = 0;
     int bufSize = 512;
     byte[] buffer = new byte[bufSize];
     while(true){
          read = bis.read(buffer);
          if(read==-1){
               break;
          }
          baf.append(buffer, 0, read);
     }
     queryResult = new String(baf.toByteArray());
     } catch (MalformedURLException e) {
          // DEBUG
          Log.e("DEBUG: ", e.toString());
     } catch (IOException e) {
          // DEBUG
          Log.e("DEBUG: ", e.toString());
     }
}
于 2010-07-20T20:39:18.333 回答
2

关于持久 HTTP 连接,情况正好相反。您应该从输入流中读取所有内容。否则 Java HTTP 客户端不知道 HTTP 请求完成,并且可以重用套接字连接。

请参阅http://java.sun.com/javase/6/docs/technotes/guides/net/http-keepalive.html

您可以做些什么来帮助 Keep-Alive?

不要忽略响应正文而放弃连接。这样做可能会导致空闲的 TCP 连接。当不再引用它们时,需要对其进行垃圾收集。

如果 getInputStream() 成功返回,则读取整个响应正文。

于 2010-06-19T16:49:37.523 回答
0

使用前者——后者比第一个没有真正的好处,而且速度有点慢;即使缓冲,逐字节读取内容也是低效的(尽管在没有缓冲时速度非常慢)。这种阅读方式在 C 语言中已经过时了。尽管在您需要找到某种结束标记的情况下可能很有用。

于 2010-10-20T16:09:32.213 回答
-1

仅当您使用BufferedInputStream-specific 方法时。

于 2010-05-08T06:31:11.110 回答