I am downloading a large repository from github 300M in size. It takes 10-15 seconds to load from my browser. On the same machine, it takes 110-120 seconds when I use the below code to download. I am wondering if I am doing wrong. Please suggest me to get the same speed (10-15 seconds) using apache http client. Or is there something better than an http client?
Apache httpclient = 4.5
java - 8
The code I used:
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();
try {
HttpGet get = new HttpGet(url.toURI());
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;
}
}
}
source
share