Java 如何从web URL获取文件名和扩展名,也可以从带有附加参数的URL获取文件名和扩展名
我试过了Java 如何从web URL获取文件名和扩展名,也可以从带有附加参数的URL获取文件名和扩展名,java,android,parsing,url-parsing,Java,Android,Parsing,Url Parsing,我试过了 new File(new URI(url).getPath()).getName() 获取名称和 fileName.substring(i+1); 分机 但是有些URL是有问题的,如果我有 https://wallpaperclicker.com/wallpaper/Download.aspx?wallfilename=samplehd-pics-87908344.jpg" 或 我需要一个能够正确处理带有附加参数的URL的解决方案。不可能从URI中找到正确的扩展名。Web服务器可
new File(new URI(url).getPath()).getName()
获取名称和
fileName.substring(i+1);
分机
但是有些URL是有问题的,如果我有
https://wallpaperclicker.com/wallpaper/Download.aspx?wallfilename=samplehd-pics-87908344.jpg"
或
我需要一个能够正确处理带有附加参数的URL的解决方案。不可能从URI中找到正确的扩展名。Web服务器可以欺骗您下载一个.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);
}
}
}
注意:代码未经测试。希望它能给你一个提示。如果你有什么想问的,请尽管问。
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);
}
}
}