java - 如何从 Web URL 以及带有附加参数的 URL 获取文件名和扩展名

标签 java android parsing url-parsing

我已经尝试过

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"

我需要一个能够正确处理带有附加参数的 URL 的解决方案。

最佳答案

不可能从 URI 中找出正确的扩展名。网络服务器可能会欺骗您下载 .sh,其中链接可能会显示它是 .jpg(符号链接(symbolic link))。

说到这个问题,如果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);
            }
        }
     }

注意:代码未经测试。希望它能给您带来提示。

关于java - 如何从 Web URL 以及带有附加参数的 URL 获取文件名和扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50369312/

相关文章:

java - 你如何阻止循环在 Java 中运行

android - RelativeLayout - 拖动自定义 View

android - 如何检查我是否已迁移到 AndroidX?

c# - 转换与解析

java - netbeans 输出线重叠

Java约束注解: Passing Parameter Value To Composite Constraint

java - 如何正确设置 JVM 时区

java - GoogleApiClient 无法在 android studio 中连接

python - 在渲染模板中将变量从 python (flask) 传递到 HTML?

python - 如何将 csv 文件读取为 dtype datetime64?