How do I save a file downloaded with HttpClient into a specific folder
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();
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();
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, e.g. 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();
}
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);