[英]Apache HttpUtils Download a File
我正在使用以下代碼下載文件並計算長度,但返回值(長度)始終為-1
private long getContentLength(String url) {
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
} catch (Exception ex) {
logException(ex);
return -1;
}
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null)
return -1;
System.out.println("Content length was: " + httpEntity.getContentLength() + " and code: " + httpResponse.getStatusLine().getStatusCode());
return httpEntity.getContentLength();
}
正在下載的文件:
boolean download100MBFile() {
getContentLength("http://cachefly.cachefly.net/100mb.test");
return true;
}
HTTP響應代碼為:200
該文件是從瀏覽器下載的,因此該文件沒有問題。 這是怎么了?
維克多(Victor)的評論激發了我使用流媒體的功能。 這是有效的更新代碼:
private long getContentLength(String url) {
outputStream.reset();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
} catch (Exception ex) {
logException(ex);
return -1;
}
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null)
return -1;
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024 * 1024 * 1024);
try {
httpEntity.writeTo(outStream);
} catch (IOException ex) {
logException(ex);
return -1;
}
return outStream.size();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.