Apache Http Client比浏览器下载慢

时间:2015-08-27 01:19:56

标签: download apache-httpclient-4.x

我正在从大小为300M的github下载一个大型存储库。从浏览器下载需要10-15秒。在同一台机器上,当我使用下面的代码下载时需要110-120秒。我想知道我做错了。请建议我使用apache http客户端获得相同的速度(10-15秒)。或者还有比http客户端更好的东西吗?

Apache httpclient = 4.5

java - 8

我使用的代码:

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

public class Downloader {

    public File download(URL url, File dstFile) {
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
        manager.setDefaultMaxPerRoute(20);
        manager.setMaxTotal(200);
        CloseableHttpClient httpclient = HttpClientBuilder.create()
                .setConnectionManager(manager)
                .build();

//  Second option: it also takes same time.
//        .setRedirectStrategy(new LaxRedirectStrategy())
//        .setMaxConnTotal(2 * 50)
//        .setMaxConnPerRoute(50)
//        .build();
//      CloseableHttpClient httpclient = HttpClients.custom()
//              .setRedirectStrategy(new LaxRedirectStrategy()) // adds HTTP REDIRECT support to GET and POST methods 
//              .build();
        try {
            HttpGet get = new HttpGet(url.toURI()); // we're using GET but it could be via POST as well
            File downloaded = httpclient.execute(get, new FileDownloadResponseHandler(dstFile));
            return downloaded;
        } catch (Exception e) {
            throw new IllegalStateException(e);
        } finally {
            IOUtils.closeQuietly(httpclient);
        }
    }

    static class FileDownloadResponseHandler implements ResponseHandler<File> {

        private final File target;

        public FileDownloadResponseHandler(File target) {
            this.target = target;
        }

        @Override
        public File handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            InputStream source = response.getEntity().getContent();
            FileUtils.copyInputStreamToFile(source, this.target);
            return this.target;
        }

    }

}

1 个答案:

答案 0 :(得分:0)

我有同样的问题;该修复程序正在实施此处的建议:https://stackoverflow.com/a/35458078/9204142,即在disableContentCompression()级别使用contentCompressionEnabled=falseRequestConfig。 修复后,速度与 curl 之一匹配。

由于我使用过Apache Camel,修复意味着在端点的URI中添加?httpClient.contentCompressionEnabled=false