首页 > 解决方案 > 如何从带有附加参数的 URL 也从 Web URL 获取文件名和扩展名

问题描述

我努力了

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

获取名称和

fileName.substring(i+1);

得到扩展

但是有些网址有问题,如果我有类似的东西,这种方法就不起作用

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"

我需要一个可以正确处理带有附加参数的 URLS 的解决方案。

标签: javaandroidparsingurl-parsing

解决方案


不可能从 URI 中找出正确的扩展名。网络服务器可以欺骗您下载 .sh 链接可能会说它是 .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);
            }
        }
     }

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


推荐阅读