首页 > 解决方案 > Apache HttpUtils 下载文件

问题描述

我正在使用以下代码下载文件并计算长度,但返回值(长度)始终为 -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

该文件是从浏览器下载的,因此该文件没有问题。这里出了什么问题?

标签: javaapache-httpclient-4.x

解决方案


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();
}

推荐阅读