Java 如何将使用HttpClient下载的文件保存到特定文件夹中

Java 如何将使用HttpClient下载的文件保存到特定文件夹中,java,apache-httpclient-4.x,Java,Apache Httpclient 4.x,我正在尝试使用HttpClient下载PDF文件。我能够得到文件,但我不知道如何将字节转换成PDF格式并将其存储在系统中的某个位置 我有以下代码,如何将其存储为PDF public ???? getFile(String url) throws ClientProtocolException, IOException{ HttpGet httpget = new HttpGet(url); HttpResponse response = htt

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

打开
FileOutputStream
并将
inputStream
中的字节保存到其中

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

编辑:

您还可以使用和以更快地下载:

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

以下是一个简单的解决方案:

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

为了记录在案,有更好(更容易)的方法来做同样的事情

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);
        }
    }
}
如果你更喜欢的话,也可以使用fluentapi

Request.Get("http://host/stuff").execute().saveContent(myFile);

您还可以使用ApacheHTTP客户端FluentAPI

Executor executor = Executor.newInstance().auth(new HttpHost(host), "user", "password"); 
executor.execute(Request.Get(url.toURI()).connectTimeout(1000)).saveContent("C:/temp/somefile");

如果您使用的是Java 7+,则可以使用本机,例如:


使用dependency
org.apache.httpcomponents:fluent hc

Request.Get(url).execute().saveContent(file);
请求来自
org.apache.http.client.fluent.Request

在我的例子中,我需要一个流,这同样简单:

inputStream = Request.Get(url).execute().returnContent().asStream();

HttpClient在内部优化读取操作。不需要使用另一个缓冲层我无法直接写入该文件路径,我必须使用
file file=new file(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),“filename.jpg”)用于写入外部存储,以便其他应用程序可以看到我的AppSwitch软件包,我需要为
请求导入该软件包。获取(“http://host/stuff“”.execute().saveContent(myFile)
在Maven中,您需要工件
org.apache.httpcomponents:fluent hc
-Java包是
org.apache.http.client.fluent.Request
这会流式传输文件还是将整个文件保存在内存中,然后保存到磁盘?让我困惑的是,在downloadAndSaveToFile方法中已经打开了一个FileOutputStream,但是当我用完整路径创建文件对象时,我得到一个“文件不存在”错误。。。你能给我们看一下将下载的这个文件保存到特定文件夹的代码吗?很抱歉,我的路径有一个输入错误。事实证明,当路径为有效路径时,我可以指定具有完整所需路径的文件对象。:-)
Request.Get(url).execute().saveContent(file);
inputStream = Request.Get(url).execute().returnContent().asStream();