【问题标题】:HttpURLConnection downloaded file nameHttpURLConnection 下载的文件名
【发布时间】:2012-06-15 06:13:56
【问题描述】:

是否可以通过 HttpURLConnection 获取下载的文件名?

URL url = new URL("http://somesite/getFile?id=12345");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setAllowUserInteraction(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
InputStream is = conn.getInputStream();

在上面的示例中,我无法从 URL 中提取文件名,但服务器会以某种方式向我发送文件名。

【问题讨论】:

  • 奇妙的问题。每当我们尝试识别在执行 url 请求时获得的文件名时,这个用例将很重要......

标签: java http inputstream httpurlconnection


【解决方案1】:

您可以使用HttpURLConnection.getHeaderField(String name) 获取Content-Disposition 标头,该标头通常用于设置文件名:

String raw = conn.getHeaderField("Content-Disposition");
// raw = "attachment; filename=abc.jpg"
if(raw != null && raw.indexOf("=") != -1) {
    String fileName = raw.split("=")[1]; //getting value after '='
} else {
    // fall back to random generated file name?
}

正如其他答案所指出的,服务器可能会返回无效的文件名,但您可以尝试一下。

【讨论】:

  • 谢谢,这个特定的服务器似乎正在为通过 get 参数请求的每个文件发送 Content-Disposition。对于直接链接,我将只解析 url。
  • 从标题中获取文件名后,从哪里下载该文件?文件将在哪里?请帮帮我。谢谢。
  • @Dharmendra 您可以使用URLConnection.getInputStream() 获取输入流并写入文件。
  • 对你的回答稍作修改String fileName = raw.split("=")[1];
  • 盲目地获取“=”之后的任何内容都会失败。
【解决方案2】:

坦率的回答是 - 除非 Web 服务器在 Content-Disposition 标头中返回文件名,否则没有真正的文件名。也许您可以将其设置为 URI 在 / 之后和查询字符串之前的最后一部分。

Map m =conn.getHeaderFields();
if(m.get("Content-Disposition")!= null) {
 //do stuff
}

【讨论】:

  • 服务器以某种方式发送文件名,事实上,如果我在网络浏览器上使用相同的链接,我可以保存文件并且它确实有一个名称。我只是不知道如何获取它。
  • 好吧,那么我相信下面的 sn-p 会有所帮助!
【解决方案3】:

检查响应中的Content-Disposition: 附件标头。

【讨论】:

    【解决方案4】:
    Map map = connection.getHeaderFields ();
                if ( map.get ( "Content-Disposition" ) != null )
                {
                    String raw = map.get ( "Content-Disposition" ).toString ();
                    // raw = "attachment; filename=abc.jpg"
                    if ( raw != null && raw.indexOf ( "=" ) != -1 )
                    {
                        fileName = raw.split ( "=" )[1]; // getting value after '='
                        fileName = fileName.replaceAll ( "\"", "" ).replaceAll ( "]", "" );
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 2012-11-06
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多