Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling downloads in Java

How would I be able to handle downloads using HttpResponse in Java? I made an HttpGet request to a specific site - the site returns the file to be downloaded. How can I handle this download? InputStream doesn't seem to be able to handle it (or maybe I'm using it the wrong way.)

like image 611
Tereno Avatar asked Apr 13 '10 20:04

Tereno


People also ask

What is Java file handling?

File handling in Java implies reading from and writing data to a file. The File class from the java.io package, allows us to work with different formats of files. In order to use the File class, you need to create an object of the class and specify the filename or directory name. For example: 1.

How do I download from InputStream?

We will use the copy(inputStream, fileOS) method to download a file into the local system. InputStream inputStream = new URL("http://example.com/my-file-path.txt").openStream(); FileOutputStream fileOS = new FileOutputStream("/Users/username/Documents/file_name. txt"); int i = IOUtils. copy(inpuStream, fileOS);


1 Answers

Assuming you're actually talking about HttpClient, Here's an SSCCE:

package com.stackoverflow.q2633002;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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;

public class Test {

    public static void main(String... args) throws IOException {
        System.out.println("Connecting...");
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet("http://apache.cyberuse.com/httpcomponents/httpclient/binary/httpcomponents-client-4.0.1-bin.zip");
        HttpResponse response = client.execute(get);

        InputStream input = null;
        OutputStream output = null;
        byte[] buffer = new byte[1024];

        try {
            System.out.println("Downloading file...");
            input = response.getEntity().getContent();
            output = new FileOutputStream("/tmp/httpcomponents-client-4.0.1-bin.zip");
            for (int length; (length = input.read(buffer)) > 0;) {
                output.write(buffer, 0, length);
            }
            System.out.println("File successfully downloaded!");
        } finally {
            if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
            if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
        }
    }

}

Works fine here. Your problem lies somewhere else.

like image 161
BalusC Avatar answered Nov 05 '22 18:11

BalusC