简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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