繁体   English   中英

Apache HttpUtils下载文件

[英]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.

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