InputStream is = entity.getContent();
String filePath = "sample.txt";
FileOutputStream fos = new FileOutputStream(new File(filePath));
int inByte;
while((inByte = is.read()) != -1)
     fos.write(inByte);
is.close();
fos.close();

EDIT:

you can also use BufferedOutputStream and BufferedInputStream for faster download:

BufferedInputStream bis = new BufferedInputStream(entity.getContent());
String filePath = "sample.txt";
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
int inByte;
while((inByte = bis.read()) != -1) bos.write(inByte);
bis.close();
bos.close();
Answer from Eng.Fouad on Stack Overflow
๐ŸŒ
CodeSignal
codesignal.com โ€บ learn โ€บ courses โ€บ efficient-api-interactions-with-java โ€บ lessons โ€บ downloading-files-from-an-api-using-javas-httpclient
Downloading Files from an API Using Java's HttpClient
Here's a basic example of downloading a file named welcome.txt from our API at http://localhost:8000/notes. This approach downloads the entire file at once, which is manageable for smaller files. This code sends a GET request and writes the response content to a local file. This method works well for small files but can strain memory for larger files. ... When dealing with large files, downloading them all at once can be inefficient and strain memory. To address this, Java's HttpClient allows handling the response as a stream using InputStream, which optimizes memory usage.
๐ŸŒ
GitHub
gist.github.com โ€บ rponte โ€บ 09ddc1aa7b9918b52029
Downloading file using Apache HttpClient (>= v4.2) with support to HTTP REDIRECT 301 and 302 when using HTTP method GET or POST ยท GitHub
Clone this repository at <script src="https://gist.github.com/rponte/09ddc1aa7b9918b52029.js"></script> Save rponte/09ddc1aa7b9918b52029 to your computer and use it in GitHub Desktop. ... Downloading file using Apache HttpClient (>= v4.2) with support to HTTP REDIRECT 301 and 302 when using HTTP method GET or POST
Discussions

java - How do I save a file downloaded with HttpClient into a specific folder - Stack Overflow
I am trying to download a PDF file with HttpClient. I am able to get the file but i am not sure how to convert the bytes into a a PDF and store it somewhere on the system ยท I have the following code, How can I store it as a PDF? public ???? getFile(String url) throws ClientProtocolException, ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Download file with Apache HttpClient - Stack Overflow
How can i do so my java code automatically download the file with the good name and extension in a specific folder ? ... you might want this header but of course it really depends on how the file is being served from the server; show a sample of the plain HTTP response received when requesting ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Download a file with HTTPClient in Java
I'm trying to write a java program that logs into a website, types in a search engine, gets the result, and then downloads the excel file that is generated from the results. So far, I can log in ok... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Download zip file using java11 HttpClient.sendAsync() - Stack Overflow
When I try to run this I get empty body so the output file will be empty as well. I noticed that using HttpURLConnection insted of Java11 HttpClient makes it work but I'd prefer to use this Java11 feature in order to send asynchronous requests. I can't understand what I'm doing wrong. EDIT: The HttpURLConnection code I'm using at the moment is the following: private void downloadVersion... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ download a file from an url in java
Download a File From an URL in Java | Baeldung
January 8, 2024 - Apache HttpClient is a popular Java library for making HTTP requests. We can use it to download files from a remote server via an HTTP request.
๐ŸŒ
amitph
amitph.com โ€บ home โ€บ java โ€บ how to download a file from url in java
How to Download a File from URL in Java - amitph
November 22, 2024 - HttpClient httpClient = ... simply create an instance of HttpClient using its builder. Next, we create HttpRequest by providing the URI, and HTTP GET method type. Then we invoke the request by attaching a BodyHandler, which returns a BodySubscriber of InputStream type. Finally, we use the input stream from the HttpResponse and use File#copy() method to write it to a Path on disk...
๐ŸŒ
Technicalkeeda
technicalkeeda.com โ€บ java-tutorials โ€บ httpclient-download-file-from-url
Loading...
November 12, 2016 - We cannot provide a description for this page right now
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/backendengineering โ€บ how to build httpclient in java to download file
r/backendengineering on Reddit: How to Build HttpClient In Java to Download File
November 28, 2023 - In this article, we will build HTTP Client that will download files from the internet. We will download image files and pdf files for this demo but we can extend it to any type of file. FYI, this code requires Java 11 since we will use HttpClient which was added in Java 11.
๐ŸŒ
Java67
java67.com โ€บ 2023 โ€บ 09 โ€บ how-to-download-file-using-http-in-java.html
How to download a file using HTTP in Java? Example | Java67
Additionally, it is also a good ... space or the file already existing, when writing the downloaded file to disk. You can also set the user agent for the HTTP request. The user agent is a string that identifies the client software and version, and information about the client ...
Top answer
1 of 1
2

Oh my god I finally got something that worked. Ok. So apparently HTTPClient can only handle 2 responses before it starts to bug out, according to here: Why does me use HttpClients.createDefault() as HttpClient singleton instance execute third request always hang

So instead, I changed my code to just get a login response, then get the excel file as a response and then quit. I also added some timeout configurations and also changed order from Exporting the file first and then Consuming the entity. I used a separate 2nd response and 2nd entity. That seemed to have helped a bit too? I'm guessing.

import java.util.List;
import java.util.ArrayList;
import org.apache.http.*;
import java.io.*;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.*;
import org.apache.http.message.*;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.entity.*;

public class hcFeb {
    public static void main (String[] args) throws ClientProtocolException, IOException {
        //Set up Cookie settings and also Timeout settings
        CookieStore cookieStore = new BasicCookieStore();
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);
        
        int CONNECTION_TIMEOUT = 80000;
        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
                .setConnectionRequestTimeout(CONNECTION_TIMEOUT)
                .setConnectTimeout(CONNECTION_TIMEOUT)
                .setSocketTimeout(CONNECTION_TIMEOUT)
                .build();
        
        //Set up HttpClient
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setDefaultCookieStore(cookieStore).disableContentCompression().build();
        
        HttpGet httpGet = new HttpGet("http://website");
        CloseableHttpResponse response = httpclient.execute(httpGet);
        
        //Create Post request to log into the website
        HttpPost httpPost = new HttpPost("http://loginwebsite");
        
        //Login to website
         List <NameValuePair> nvps = new ArrayList <NameValuePair>();

            nvps.add(new BasicNameValuePair("user","username"));
            nvps.add(new BasicNameValuePair("password","password"));
            nvps.add(new BasicNameValuePair("button", "Login"));
            nvps.add(new BasicNameValuePair("task", "extlogin"));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            response = httpclient.execute(httpPost);

        
        try{
            System.out.println(response.getStatusLine());   
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);                
        } finally{
        }
        
        //Send request for Excel file and download it.
        String link = "http://website.com/uri?ActSts=Edit&task=filter&Field=Plant";
        HttpGet get = new HttpGet(link);
        
        //maybe create new response
        HttpResponse response2;

        try{
            response2 = httpclient.execute(get,context);
            System.out.println(response2.getStatusLine());  
            HttpEntity entity1 = response2.getEntity();


            if (entity1 != null) {
                System.out.println("Entity isn't null");
                
                InputStream is = entity1.getContent();
                String filePath = "C:\\Users\\windowsUserName\\Downloads\\WODETAIL_List.xls";
                FileOutputStream fos = new FileOutputStream(new File(filePath));
                
                byte[] buffer = new byte[5600];
                int inByte;
                while((inByte = is.read(buffer)) > 0)
                    fos.write(buffer,0,inByte);
                is.close();
                fos.close();
                
                System.out.println("Excel File recieved");                  
                
                
                EntityUtils.toString(response2.getEntity());
                EntityUtils.consume(entity1);
                
            }
            
        } catch (ConnectionPoolTimeoutException e){
            //response.close();
            System.out.println(e.getMessage());
        } catch (IOException e){
            System.out.println(e.getMessage());
        }
        
    }
}
๐ŸŒ
MagicMonster
magicmonster.com โ€บ kb โ€บ prg โ€บ java โ€บ net โ€บ apache_httpclient
Using Apache Commons HttpClient to download HTTP data
package com.magicmonster.sample; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URI; public class HttpClientSnippet { public static void main(String[] args) throws Exception { String url = "http://magicmonster.com"; URI uri = new URI(url); HttpGet httpget = new HttpGet(uri); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpget); // check response headers.
๐ŸŒ
GitConnected
levelup.gitconnected.com โ€บ how-to-build-httpclient-in-java-to-download-file-7085c2b6a3d0
How to Build HttpClient In Java to Download File | by Suraj Mishra | Level Up Coding
November 5, 2023 - In this article, we will build HTTP Client that will download files from the internet. We will download image files and pdf files for this demo but we can extend it to any type of file. FYI, this code requires Java 11 since we will use HttpClient which was added in Java 11.
๐ŸŒ
Tech Coil
techcoil.com โ€บ blog โ€บ how-to-download-a-file-via-http-get-and-http-post-in-java-without-using-any-external-libraries
How to download a file via HTTP GET and HTTP POST in Java without using any external libraries
December 3, 2018 - Generally, downloading a file from a HTTP server endpoint via HTTP GET consists of the following steps: Construct the HTTP GET request to send to the HTTP server. Send the HTTP request and receive the HTTP Response from the HTTP server.
๐ŸŒ
DEV Community
dev.to โ€บ noelopez โ€บ http-client-api-in-java-part-3-1bgj
Http Client API in Java: Managing Files - DEV Community
April 29, 2023 - The purpose of this article is to show how to use the Http Client API to upload/download file contents from a REST endpoint.
๐ŸŒ
Medium
pkslow.medium.com โ€บ multiple-ways-to-download-files-from-internet-in-java-ced5d3aaae2c
Multiple Ways to Download Files from Internet in Java | by Larry Deng | Medium
April 3, 2023 - private static void okHttpClient(String downloadUrl) { try { OkHttpClient client = new OkHttpClient(); okhttp3.Request request = new okhttp3.Request.Builder().url(downloadUrl).build(); okhttp3.Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Failed to download file: " + response); } FileOutputStream fos = new FileOutputStream("pkslow.okHttpClient.html"); fos.write(response.body().bytes()); fos.close(); } catch (Exception e) { throw new RuntimeException(e); } } ... <dependency> <groupId>org.asynchttpclient</groupId> <artifactId>async-http-client</artifactId> <version>2.12.3</version> </dependency>
๐ŸŒ
OpenJDK
bugs.openjdk.org โ€บ browse โ€บ JDK-8212926
HttpClient does not retrieve files with large sizes over HTTP/1.1
Http Client that will use HTTP 1.1 (for the example file I provided this is important as cloudflare will server up HTTP 2 if we don't specificly request HTTP 1.1) 2. Create a request to download a file with one of the specified sizes (for example: https://map.usbcraft.net/file/usbpc-downlo...