2017-05-29 112 views
3

即时消息试图做的是用httpclient下载文件。目前我的代码如下。用Apache HttpClient下载文件

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

我的下载网址是类似的东西:http://example.com/file/afz938f348dfa3

正如你可以看到有没有扩展名的文件(url中至少),但是,当我去到URL使用普通浏览器,它确实下载了文件“asdasdaasda.txt”或“asdasdasdsd.pdf”(该名称与url不同,扩展名并不总是相同,取决​​于我试图下载的内容)。

我的HTTP响应看起来是这样的:

日期:星期一,2017年5月29日14点57分十四秒格林尼治标准时间服务器:Apache/2.4.10 内容处置:附件; filename =“149606814324_testfile.txt” Accept-Ranges:bytes Cache-Control:public,max-age = 0最后修改日期: Mon,29 May 2017 14:29:06 GMT Etag:W /“ead-15c549c4678-gzip “ Content-Type:text/plain;字符集= UTF-8有所不同:接受编码 内容编码:gzip的Content-Length:2554保持活动:超时= 5, 最大= 100连接:保持活动

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

+2

你可能想[这个头(HTTPS ://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition),但当然这取决于如何从服务器提供文件;请求URL时,显示普通HTTP响应的样本接收或提供您使用的是能得到更多的帮助 –

+0

@OvidiuDolha 日期的有效访问网址:星期一,2017年14时57分十四秒GMT 服务器5月29日:Apache/2.4.10 内容处置:附件;文件名= “149606814324_testfile.txt” 接受-范围:字节 缓存控制:公众,最大年龄= 0 的Last-Modified:星期一,2017年5月29日14时29分06秒GMT 的Etag:W/“ead-15c549c4678-gzip” Content-Type:text/plain;字符集= UTF-8 有所不同:接受编码 内容编码:gzip 内容长度:2554 保持活动:超时= 5,最大= 100 连接:保持活动 – retArdos

回答

2

你可以从你的回应的content-disposition header

首先,文件名和扩展名获得头,然后分析它的文件名作为explained here,即:

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

非常感谢,你的代码似乎工作正常。然而,我编写了这一行的第一个版本:\t String fileName = disposition.substring(disposition.indexOf(“\”“)+ 1,disposition.lastIndexOf(”\“”)); 而不是String fileName = disposition.replaceFirst(“(?i)^。* filename = \”([^ \“] +)。”。* $“,”$ 1“); 这是什么区别两个,因为他们似乎都给出了相同的结果 – retArdos

相关问题