buffer - 读取 HttpURLConnection InputStream - 手动缓冲区还是 BufferedInputStream?

标签 buffer inputstream httpurlconnection bufferedinputstream

在读取 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% 好?

最佳答案

我在我的博客上的一篇关于在 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());
     }
}

关于buffer - 读取 HttpURLConnection InputStream - 手动缓冲区还是 BufferedInputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2793168/

相关文章:

PHP:使用多行启动变量

Java - 从缓冲读取器(从套接字)读取正在暂停线程

.net - TcpClient.ReceiveBufferSize 会影响底层帧大小吗?

string - 在 Scala 中将输入流转换为字符串的惯用方法

Java:使用 HttpURLConnection 的 HTTP PUT

android - HttpURLConnection setReadTimeout 不工作

node.js - Node JS 中的 UInt16LE、UInt16BE 等是什么?

ios - 使用套接字发送 HTTP POST 请求

java - Android - 非 UI 线程渲染我的 UI 无响应

java - 在android中下载zip文件