2017-04-08 87 views
0

我使用这段代码稍后从URL下载文件。Java URLConnection标头名称

  URL url = new URL("http://smarthome-de.censored.net/Installer.zip"); 
      URLConnection conn = url.openConnection(); 
      int size = conn.getContentLength(); 
      String type = conn.getContentType(); 

有没有办法从URL中捕获文件名? 我可以将“Installer.zip”存储到字符串中,因为它已知,因此无需获取该值。

我找到了getContentType()给我的类型。可悲的是,我没有找到任何名称的方法。

回答

0

您可以从Content-Disposition头获取文件名:

String contentDisposition = conn.getHeaderField("Content-Disposition"); 

请注意,这头由服务器设置,并且不保证存在。下载文件的HTTP客户端使用Content-Disposition(如果存在),或者默认为URL的最后一部分(在您的示例中为Installer.zip)。

内容处置头内容是这样的:

Content-Disposition: attachment; filename="Installer.zip" 

你必须解析头值提取的文件名部分。 有关详细信息,你可以看看这里:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition