【发布时间】:2012-11-06 08:24:49
【问题描述】:
我们通常在android开发中从服务器响应中获取数据。
/*
* get server response inputStream
*/
InputStream responseInputStream;
解决方案1:通过多次读取获取响应字符串。
/*
* get server response string
*/
StringBuffer responseString = new StringBuffer();
responseInputStream = new InputStreamReader(conn.getInputStream(),"UTF-8");
char[] charBuffer = new char[bufferSize];
int _postion = 0;
while ((_postion=responseInputStream.read(charBuffer)) > -1) {
responseString.append(charBuffer,0,_postion);
}
responseInputStream.close();
解决方案 2:仅读取一次响应。
String responseString = null;
int content_length=1024;
// we can get content length from response header, here assign 1024 for simple.
responseInputStream = new InputStreamReader(conn.getInputStream(),"UTF-8");
char[] charBuffer = new char[content_length];
int _postion = 0;
int position = responseInputStream.read(charBuffer)
if(position>-1){
responseString = new String(charBuffer,0,position );
}
responseInputStream.close();
哪种解决方案的性能更好?为什么?
注意事项:服务器响应小于1M字节的json格式数据。
【问题讨论】:
-
第二个更快
-
我倾向于使用第一个解决方案,因为这样我就可以确定缓冲区大小,如果您不将结果视为字符串,这通常是一个有效点。
-
@njzk2 你推荐解决方案2?
-
第二种解决方案的一点是您不检查实际读取长度,并且您没有机制以防它未完全读取。
-
另外,为了简单起见,有更广泛的选择,我倾向于使用 EntityUtils.toString,因为我使用的是 HttpClient。看代码,基本上是第一种解决方案(不过是捆绑的)
标签: android inputstream inputstreamreader