简体   繁体   English

Apache HttpUtils下载文件

[英]Apache HttpUtils Download a File

I am using the following code to download file and calculate the length but the return value(length) is always -1 我正在使用以下代码下载文件并计算长度,但返回值(长度)始终为-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();
    }

The file being downloaded: 正在下载的文件:

boolean download100MBFile() {
       getContentLength("http://cachefly.cachefly.net/100mb.test");
       return true;
    }

The HTTP response code is: 200 HTTP响应代码为:200

The file gets downloaded from the browser, so there is no issue with the file. 该文件是从浏览器下载的,因此该文件没有问题。 What is going wrong here? 这是怎么了?

The comment by Victor sparked me to use a stream. 维克多(Victor)的评论激发了我使用流媒体的功能。 Here is the updated code which works: 这是有效的更新代码:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM