Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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, 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;         } 
like image 827
code511788465541441 Avatar asked Jun 09 '12 10:06

code511788465541441


People also ask

How to download file with HttpClient in Java?

Using Java HttpClient 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.


1 Answers

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(); 
like image 128
Eng.Fouad Avatar answered Oct 07 '22 19:10

Eng.Fouad