今天在實(shí)用webview下載文件的時候徘公,本來是想自己拼接一個文件名的,后來哮针,還是決定直接拿要下載的文件名关面。
那么怎么獲取文件名呢?
其實(shí)系統(tǒng)為我們提供了一個很實(shí)用的工具類
android webkit包下的URLUtil工具類
獲取文件名一個方法搞定
gussFileName()
String fileName = URLUtil.guessFileName(url,contentDisposition,mimetype);
看源碼 第一個參數(shù)就是要文件的下載url十厢,一定要是文件的下載url等太,而不是所在的網(wǎng)頁的url。也就是說蛮放,這個地址是可以直接在瀏覽器或者迅雷上面下載的缩抡。
第二個參數(shù) Content-disposition 是 MIME 協(xié)議的擴(kuò)展,MIME 協(xié)議指示 MIME 用戶代理如何顯示附加的文件
第三個參數(shù) mimetype 返回內(nèi)容的Mime-type
/**
* Guesses canonical filename that a download would have, using
* the URL and contentDisposition. File extension, if not defined,
* is added based on the mimetype
* @param url Url to the content
* @param contentDisposition Content-Disposition HTTP header or {@code null}
* @param mimeType Mime-type of the content or {@code null}
*
* @return suggested filename
*/
public static final String guessFileName
這幾個參數(shù)在webview的DownloadListener的監(jiān)聽中返回
mWebview.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Log.i(TAG,url + "--" + userAgent + "--" + contentDisposition + "--" + mimetype + "--" + contentLength);
String fileName = URLUtil.guessFileName(url,contentDisposition,mimetype);
}
});
除了guessFileName包颁,URLUtil中還有一些其他比較實(shí)用的方法缝其。
比如,下面這個verifyURLEncoding(url)
verifyURLEncoding()
判斷url是否正確的編碼
/**
* @return {@code true} if the url is correctly URL encoded
*/
static boolean verifyURLEncoding(String url) {
int count = url.length();
if (count == 0) {
return false;
}
int index = url.indexOf('%');
while (index >= 0 && index < count) {
if (index < count - 2) {
try {
parseHex((byte) url.charAt(++index));
parseHex((byte) url.charAt(++index));
} catch (IllegalArgumentException e) {
return false;
}
} else {
return false;
}
index = url.indexOf('%', index + 1);
}
return true;
}
isValidUrl()
判斷url是否合法
/**
* @return {@code true} if the url is valid.
*/
public static boolean isValidUrl(String url) {
if (url == null || url.length() == 0) {
return false;
}
return (isAssetUrl(url) ||
isResourceUrl(url) ||
isFileUrl(url) ||
isAboutUrl(url) ||
isHttpUrl(url) ||
isHttpsUrl(url) ||
isJavaScriptUrl(url) ||
isContentUrl(url));
}
這個方法的源碼中調(diào)用了其他幾個比較實(shí)用的方法徘六,比如内边,對http https的判斷。我們就不需要單獨(dú)去寫代碼待锈,直接調(diào)用這個工具類的方法就可以了漠其。
/**
* @return {@code true} if the url is an http: url.
*/
public static boolean isHttpUrl(String url) {
return (null != url) &&
(url.length() > 6) &&
url.substring(0, 7).equalsIgnoreCase("http://");
}
這個是http的判斷,代碼比我們平常自己寫的嚴(yán)謹(jǐn)多了竿音。
還有幾個方法也是比較實(shí)用的和屎,這里就不一一介紹了,直接源碼里面就可以查看春瞬。