Skip to content

Instantly share code, notes, and snippets.

Last active Dec 23, 2022
What would you like to do?
Downloading file using Apache HttpClient (>= v4.2) with support to HTTP REDIRECT 301 and 302 when using HTTP method GET or POST
public class App {
public static void main(String[] args) throws MalformedURLException {
URL rightUrl = new URL("");
URL redirectableUrl = new URL(""); // redirected to
Downloader downloader = new Downloader();
System.out.println("Downloading file through right Url...");, new File("main-ok.css"));
System.out.println("Downloading file through a redirectable Url...");, new File("main-redirected.css"));
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.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
public class Downloader {
public File download(URL url, File dstFile) {
CloseableHttpClient httpclient = HttpClients.custom()
.setRedirectStrategy(new LaxRedirectStrategy()) // adds HTTP REDIRECT support to GET and POST methods
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 {
static class FileDownloadResponseHandler implements ResponseHandler<File> {
private final File target;
public FileDownloadResponseHandler(File target) { = target;
public File handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
InputStream source = response.getEntity().getContent();
Copy link

Perfectly works, Thanks

Copy link

anfb commented Jan 14, 2019

Great job! 👍

Copy link

It helped 👍

Copy link

It helped +1

Copy link

teagithub commented Jul 13, 2019

Thank you!
Tips for others who want to use it: if use maven , pom.xml needs to add the following from

Copy link

AyeshW commented Oct 15, 2019

It worked perfectly. Thank you!

Copy link

Harshad-Dange commented Jun 27, 2022

I have been looking for this since so long, and finally found it. My use case was to store api response into zip file as its in byte array but was not able to store it into .zip in RestAssured.
If any one knows the alternative for this in RestAssured would be helpful.
Thanks in Advance !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment