我使用Apache HTTP客户端从Android上的url获取文件流,我想检查流的头以确定是否应该加载整个文件,以避免无意义的网络资源成本。
现在,我使用以下代码获取stream并从中读取前几个字节:
response = mClient.execute(method, localcontext);
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
byte[] ints = new byte[2];
instream.read(ints);
}
我想知道在上面的过程中是否会加载整个文件。我应该显式地关闭流吗?如何?
谢谢~
更好的方法是使用HEAD方法。它只是返回http报头,没有实际的内容或正文。
示例(来自官方网站)
HeadMethod head = new HeadMethod("http://jakarta.apache.org");
// execute the method and handle any error responses.
...
// Retrieve all the headers.
Header[] headers = head.getResponseHeaders();
一旦有了标题,就可以检查它们,然后相应地进行另一个GET/POST调用来实际下载内容。