public static String getFileName(String url) {
String filename = "";
boolean isok = false;
// 从UrlConnection中获取文件名称
try {
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
if (conn == null) {
return null;
}
Map<String, List<String>> hf = conn.getHeaderFields();
if (hf == null) {
return null;
}
Set<String> key = hf.keySet();
if (key == null) {
return null;
}
// Log.i("test", "getContentType:" + conn.getContentType() + ",Url:"
// + conn.getURL().toString());
for (String skey : key) {
List<String> values = hf.get(skey);
for (String value : values) {
String result;
try {
result = new String(value.getBytes("ISO-8859-1"), "GBK");
int location = result.indexOf("filename");
if (location >= 0) {
result = result.substring(location
+ "filename".length());
filename = result
.substring(result.indexOf("=") + 1);
isok = true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}// ISO-8859-1 UTF-8 gb2312
}
if (isok) {
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 从路径中获取
if (filename == null || "".equals(filename)) {
filename = url.substring(url.lastIndexOf("/") + 1);
}
return filename;
}
http://blog.sina.com.cn/s/blog_8a7200cd01014ukt.html
根据URL得到文件名称
最新推荐文章于 2024-07-26 03:05:56 发布