读取 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);
}
EDIT一般来说,我对 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());
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)