如何将使用HttpClient下载的文件保存到特定文件夹中
我正在尝试使用HttpClient下载PDF文件。 我能够获取文件,但我不知道如何将字节转换为PDF并将其存储在系统的某个位置
我有以下代码,如何将其存储为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();
编辑:
您还可以使用BufferedOutputStream和BufferedInputStream来加快下载速度:
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();
只是为了记录,有更好(更容易)的方法来做同样的事情
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); } } }
或者如果人们更喜欢它,可以使用流畅的API
Request.Get("http://host/stuff").execute().saveContent(myFile);
这是一个使用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()
很棒,因为它处理缓冲。 但是,此解决方案不是很可扩展:
- 您无法指定目标文件名和目录
- 您可能希望以不同的方式存储文件,例如在数据库中。 在这种情况下不需要文件。
更具可扩展性的解决方案涉及两个function:
public void downloadFile(String url, OutputStream target) throws ClientProtocolException, IOException{ //... if (entity != null) { //... InputStream inputStream = entity.getContent(); IOUtils.copy(inputStream, target); } }
和帮助方法:
public void downloadAndSaveToFile(String url, File targetFile) { OutputStream outputStream = new FileOutputStream(targetFile); downloadFile(url, outputStream); outputStream.close(); }
打开FileOutputStream
并将inputStream
的字节保存到它。
您还可以使用Apache http客户端流畅的API
Executor executor = Executor.newInstance().auth(new HttpHost(host), "user", "password"); executor.execute(Request.Get(url.toURI()).connectTimeout(1000)).saveContent("C:/temp/somefile");
- 尝试进行客户端服务器ssl身份validation时,Tomcat 7获取SSLv2Hello被禁用错误
- 使用RestTemplate进行基本身份validation(3.1)
- 如何在Apache HTTP Client 4中使用Socks 5代理?
- 从NameValuePairs列表创建UrlEncodedFormEntity会抛出NullPointerException
- 修复java.net.SocketTimeoutException:读取超时
- 信任过期的证书
- 如何从apache httpclient 4中禁用默认请求标头?
- Android JAVA到SharePoint 2013 NTLM 401取消授权
- 如何用RequestConfig替换不推荐使用的httpClient.getParams()?