使用Apache HttpClient下载文件 [英] Download file with Apache HttpClient

查看:260
本文介绍了使用Apache HttpClient下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即时通讯试图通过httpclient下载文件。目前,我的代码如下。

what im trying to do is to download a file with httpclient. At the moment my code is the following.

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(downloadURL);     


    HttpResponse response = client.execute(request);

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        FileOutputStream fos = new FileOutputStream("C:\\file");
        entity.writeTo(fos);
        fos.close();
    }

我的下载URL是这样的: http://example.com/file/afz938f348dfa3

My download URL is something like that: http://example.com/file/afz938f348dfa3

如您所见该文件没有扩展名(至少在URL中没有),但是,当我使用普通浏览器访问该URL时,它会下载文件 asdasdaasda.txt或 asdasdasdsd.pdf(名称与网址和扩展名并不总是相同,具体取决于我尝试下载的内容)。

As you can see there is no extension to the file (in the url at least) however, when i go to the url with a normal browser, it does download the file "asdasdaasda.txt" or "asdasdasdsd.pdf" (the name is different from the url and the extenstion is not always the same, depends on what im trying to download).

我的http响应如下:

My http response looks like this:


日期:5月29日,星期一2017 14:57:14 GMT服务器:Apache / 2.4.10
内容处置:附件; filename = 149606814324_testfile.txt
接受范围:字节缓存控制:公共,最大年龄= 0最后修改时间:
,2017年5月29日星期一14:29:06 GMT标记:W / ead-15c549c4678-gzip
内容类型:文本/纯文本; charset = UTF-8变体:接受编码
内容编码:gzip内容长度:2554保持活动:超时= 5,
最大= 100连接:保持活动

Date: Mon, 29 May 2017 14:57:14 GMT Server: Apache/2.4.10 Content-Disposition: attachment; filename="149606814324_testfile.txt" Accept-Ranges: bytes Cache-Control: public, max-age=0 Last-Modified: Mon, 29 May 2017 14:29:06 GMT Etag: W/"ead-15c549c4678-gzip" Content-Type: text/plain; charset=UTF-8 Vary: Accept-Encoding Content-Encoding: gzip Content-Length: 2554 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive

我该怎么做,我的Java代码自动在特定文件夹中下载具有良好名称和扩展名的文件?

How can i do so my java code automatically download the file with the good name and extension in a specific folder ?

推荐答案

您可以从响应的 内容处置标头

You can get the file name and extension from your response's content-disposition header

首先获取标头,然后将其解析为文件名,如在此处解释,即:

First get the header then parse it for the filename as explained here, i.e:

HttpEntity entity = response.getEntity();
if (entity != null) {
    String name = response.getFirstHeader('Content-Disposition').getValue();
    String fileName = disposition.replaceFirst("(?i)^.*filename=\"([^\"]+)\".*$", "$1");
    FileOutputStream fos = new FileOutputStream("C:\\" + fileName);
    entity.writeTo(fos);
    fos.close();
}

这篇关于使用Apache HttpClient下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆