读取HttpURLConnection InputStream-手动缓冲区还是BufferedInputStream? [英] Reading HttpURLConnection InputStream - manual buffer or BufferedInputStream?

查看:403
本文介绍了读取HttpURLConnection InputStream-手动缓冲区还是BufferedInputStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When reading the InputStream of an HttpURLConnection, is there any reason to use one of the following over the other? I've seen both used in examples.

手动缓冲区:

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

BufferedInputStream

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连接,我不能只等到输入流为空时才读对吗?在那种情况下,我是否不需要读取消息长度并只读取该长度的输入流?

EDIT I'm still new to HTTP in general but one consideration that comes to mind is that if I am using a persistent HTTP connection, I can't just read until the input stream is empty right? In that case, wouldn't I need to read the message length and just read the input stream for that length?

同样,如果不使用持久连接,我包含的代码100%可以正确读取流?

And similarly, if NOT using a persistent connection, is the code I included 100% good to go in terms of reading the stream properly?

推荐答案

我在说一种好的方法关于我在Android中使用JSON的帖子中的内容。 http:// blog .andrewpearson.org / 2010/07 / android-why-to-use-json-and-how-to-use.html 。我将在下面发布相关文章的相关部分(该代码相当通用):

I talk about a good way to do it on my blog in a post about using JSON in android. http://blog.andrewpearson.org/2010/07/android-why-to-use-json-and-how-to-use.html. I will post the relevant part of the relevant post below (the code is pretty generalizable):

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

这篇关于读取HttpURLConnection InputStream-手动缓冲区还是BufferedInputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆