cod*_*441 36 java apache-httpclient-4.x
我正在尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)
Eng*_*uad 42
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();
Run Code Online (Sandbox Code Playgroud)
编辑:
您还可以使用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();
Run Code Online (Sandbox Code Playgroud)
ok2*_*k2c 36
只是为了记录,有更好(更容易)的方法来做同样的事情
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者如果人们更喜欢它,可以使用流畅的API
Request.Get("http://host/stuff").execute().saveContent(myFile);
Run Code Online (Sandbox Code Playgroud)
Tom*_*icz 23
这是一个简单的解决方案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;
Run Code Online (Sandbox Code Playgroud)
IOUtils.copy()很棒,因为它处理缓冲.但是,此解决方案不是很可扩展:
更具可扩展性的解决方案涉及两个功能:
public void downloadFile(String url, OutputStream target) throws ClientProtocolException, IOException{
//...
if (entity != null) {
//...
InputStream inputStream = entity.getContent();
IOUtils.copy(inputStream, target);
}
}
Run Code Online (Sandbox Code Playgroud)
和辅助方法:
public void downloadAndSaveToFile(String url, File targetFile) {
OutputStream outputStream = new FileOutputStream(targetFile);
downloadFile(url, outputStream);
outputStream.close();
}
Run Code Online (Sandbox Code Playgroud)
使用依赖项org.apache.httpcomponents:fluent-hc:
Request.Get(url).execute().saveContent(file);
Run Code Online (Sandbox Code Playgroud)
请求来自org.apache.http.client.fluent.Request.
就我而言,我需要一个流,这同样简单:
inputStream = Request.Get(url).execute().returnContent().asStream();
Run Code Online (Sandbox Code Playgroud)