java - 如何从带有附加参数的 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 的解决方案。
解决方案
不可能从 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);
}
}
}
注意:代码未经测试。希望它能给你一个提示。
推荐阅读
- python - 寻找计算两条曲线之间距离的解决方案
- javascript - 匹配 `.` 但不匹配 `am` 的正则表达式
- javascript - d3.js 数据导入但条形图不显示
- swift - 仅在有足够空间时才显示 SwiftUI 视图
- javascript - 到底是什么导致这个脚本失败?没有控制台错误,在 CodePen 中工作正常
- amazon-web-services - 在 AWS 中为转移的域创建托管区域并链接到 SES 时出现问题
- thymeleaf - 在 Thymeleaf th:action 中使用布尔值
- search - 对于患有严重 ADHD 的人来说,学习如何正确搜索 stackoverflow 的简单问题有哪些好的提示?
- swiftui - 如何单独和整体同时控制视图
- python - BoxLayou 在 Kivy 上重复