代码之家  ›  专栏  ›  技术社区  ›  AndreaF

如何从web URL获取文件名和扩展名,也可以从URL获取其他参数

  •  1
  • AndreaF  · 技术社区  · 6 年前

    我试过了

    new File(new URI(url).getPath()).getName()
    

    获取名称和

    fileName.substring(i+1);
    

    获取扩展名

    但是有些URL是有问题的,如果我有

    https://wallpaperclicker.com/wallpaper/Download.aspx?wallfilename=samplehd-pics-87908344.jpg"
    

    https://spxt-sjc2-1.cdnagram.com/t51.2885-15/s980x480/e35/20969138_31213_564630462529635_5170096177993632_n.jpg?ig_cache_key=M0003NTyMTc3MjY5MDE4Nw%3D%3D.2"
    

    我需要一个解决方案,可以正确处理也URL与其他参数。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Sahith Vibudhi    6 年前

    无法从URI中找到正确的扩展名。Web服务器可以欺骗您下载。链接可能会说它在哪里。jpg(符号链接)。

    针对这个问题,如果url解析不起作用,您可以建立连接并使用getContentType等获取服务器设置的信息。

        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();
    
        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");
            String contentType = httpConn.getContentType();
    
            if (disposition != null) {
                // extracts file name from header field
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10,
                            disposition.length() - 1);
                }
            }
         }
    

    注意:代码未经测试。希望它能给你一个提示。