Android 獲取下載文件的真實名字

m8x2 9年前發布 | 2K 次閱讀 Java Android

    public static String getReallyFileName(String url) {
String filename = "";
URL myURL;
HttpURLConnection conn = null;
if (url == null || url.length() < 1) {
return null;
}

        try {  
            myURL = new URL(url);  
            conn = (HttpURLConnection) myURL.openConnection();  
            conn.connect();  
            conn.getResponseCode();  
            URL absUrl = conn.getURL();// 獲得真實Url  
            Log.e("H3c", "x:" + absUrl);  
            // 打印輸出服務器Header信息  
            // Map<String, List<String>> map = conn.getHeaderFields();  
            // for (String str : map.keySet()) {  
            // if (str != null) {  
            // Log.e("H3c", str + map.get(str));  
            // }  
            // }  
            filename = conn.getHeaderField("Content-Disposition");// 通過Content-Disposition獲取文件名,這點跟服務器有關,需要靈活變通  
            if (filename == null || filename.length() < 1) {  
                filename = absUrl.getFile();  
            }  
        } catch (MalformedURLException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (conn != null) {  
                conn.disconnect();  
                conn = null;  
            }  
        }  

        return filename;  
    }  </pre> 


 本文由用戶 m8x2 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!