简体   繁体   中英

How do I save a file downloaded with HttpClient into a specific folder

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 aa 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, IOException{

            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                long len = entity.getContentLength();
                InputStream inputStream = entity.getContent();
                // How do I write it?
            }

            return null;
        }
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();

Just for the record there are better (easier) ways of doing the same

File myFile = new File("mystuff.bin");

CloseableHttpClient client = HttpClients.createDefault();
try (CloseableHttpResponse response = client.execute(new HttpGet("http://host/stuff"))) {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try (FileOutputStream outstream = new FileOutputStream(myFile)) {
            entity.writeTo(outstream);
        }
    }
}

Or with the fluent API if one likes it better

Request.Get("http://host/stuff").execute().saveContent(myFile);

Here is a simple solution using IOUtils.copy() :

File targetFile = new File("foo.pdf");

if (entity != null) {
    InputStream inputStream = entity.getContent();
    OutputStream outputStream = new FileOutputStream(targetFile);
    IOUtils.copy(inputStream, outputStream);
    outputStream.close();
}

return targetFile;

IOUtils.copy() is great because it handles buffering. However this solution is not very scalable:

  • you cannot specify target file name and directory
  • you might wish to store the files in a different way, eg in a database. Files aren't needed in this scenario.

Much more scalable solution involves two functions:

public void downloadFile(String url, OutputStream target) throws ClientProtocolException, IOException{
    //...
    if (entity != null) {
    //...
        InputStream inputStream = entity.getContent();
        IOUtils.copy(inputStream, target);
    }
}

And a helper method:

public void downloadAndSaveToFile(String url, File targetFile) {
    OutputStream outputStream = new FileOutputStream(targetFile);
    downloadFile(url, outputStream);
    outputStream.close();
}

Using dependency org.apache.httpcomponents:fluent-hc :

Request.Get(url).execute().saveContent(file);

Request is from org.apache.http.client.fluent.Request .

In my case I needed a stream, this is equally simple:

inputStream = Request.Get(url).execute().returnContent().asStream();

If you are using Java 7+, you can use the native Files.copy(InputStream in, Path target, CopyOption... options) , eg:

HttpEntity entity = response.getEntity();

try (InputStream inputStream = entity.getContent()) {
    Files.copy(inputStream, Paths.get(filePathString), StandardCopyOption.REPLACE_EXISTING);
}

打开一个FileOutputStream并将inputStream的字节保存到它。

You can also use Apache http client fluent API

Executor executor = Executor.newInstance().auth(new HttpHost(host), "user", "password"); 
executor.execute(Request.Get(url.toURI()).connectTimeout(1000)).saveContent("C:/temp/somefile");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM