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;
    }

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *