43

我正在尝试使用 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;
        }
4

7 回答 7

48
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();

编辑:

您还可以使用BufferedOutputStreamBufferedInputStream来加快下载速度:

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();
于 2012-06-09T11:04:35.227 回答
45

只是为了记录,有更好(更简单)的方法来做同样的事情

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);
        }
    }
}

或者如果有人更喜欢它,可以使用 fluent API

Request.Get("http://host/stuff").execute().saveContent(myFile);
于 2015-08-18T09:22:13.457 回答
25

这是一个简单的解决方案,使用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()很棒,因为它处理缓冲。但是,此解决方案的可扩展性不是很高:

  • 您不能指定目标文件名和目录
  • 您可能希望以不同的方式存储文件,例如在数据库中。在这种情况下不需要文件。

更具可扩展性的解决方案涉及两个功能:

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();
}
于 2012-06-09T11:05:08.943 回答
3

使用依赖org.apache.httpcomponents:fluent-hc

Request.Get(url).execute().saveContent(file);

请求来自org.apache.http.client.fluent.Request

就我而言,我需要一个流,这同样简单:

inputStream = Request.Get(url).execute().returnContent().asStream();
于 2018-11-10T11:35:56.223 回答
2

如果您使用的是 Java 7+,则可以使用本机Files.copy(InputStream in, Path target, CopyOption... options),例如:

HttpEntity entity = response.getEntity();

try (InputStream inputStream = entity.getContent()) {
    Files.copy(inputStream, Paths.get(filePathString), StandardCopyOption.REPLACE_EXISTING);
}
于 2018-10-17T17:37:59.673 回答
1

打开 aFileOutputStream并将字节保存inputStream到其中。

于 2012-06-09T11:04:19.097 回答
0

您还可以使用 Apache http 客户端 fluent API

Executor executor = Executor.newInstance().auth(new HttpHost(host), "user", "password"); 
executor.execute(Request.Get(url.toURI()).connectTimeout(1000)).saveContent("C:/temp/somefile");
于 2018-08-22T11:38:08.290 回答