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; }
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With