3

当读取HttpURLConnection的InputStream时,是否有任何理由使用下列其中之一:我见过两个例子。阅读HttpURLConnection InputStream - 手动缓冲区或BufferedInputStream?

手工缓冲:

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

同样,如果没有使用持久连接,我认为在正确读取数据流方面100%的好处包括了哪些代码?

+0

什么是'ByteArrayBuffer'?但是当你可以处理字节数组时,从来没有任何理由处理单个字节。 – EJP 2017-09-29 11:12:20

回答

-1

只有在您使用BufferedInputStream特定的方法。

+0

对问题添加了进一步的说明。 – stormin986 2010-05-08 06:34:20

+0

'BufferedInputStream'特定的方法如什么?它不会导出除InputStream定义的方法之外的任何方法。 – EJP 2017-09-29 11:06:24

1

关于持久HTTP连接,它恰恰相反。你应该从输入流读取所有内容。否则,Java HTTP客户端不知道HTTP请求已完成,并且可以重新使用套接字连接。

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

你能做些什么来帮助保活?

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

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

5

我在一篇关于在an​​droid中使用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()); 
    } 
} 
+1

有一个确定但要解决的问题:您应该始终指定用于将字节转换为字符串的编码(新字符串(baf.toByteArray(),“UTF-8”))。 – StaxMan 2010-10-20 16:06:35

0

使用前者 - 后者在第一个没有实际利益,而且是有点慢;即使经过缓冲,逐字节地读取数据也是低效的(尽管在没有缓冲的情况下速度很慢)。这种阅读方式与C一起流行;尽管在需要查找某种结束标记的情况下可能会有用。