使用DownLoadManager.Request从URL下载文件时下载不成功

时间:2016-12-29 13:34:55

标签: android android-download-manager

我尝试使用DownloadManager从服务器下载文件但是无法下载并说下载失败,我已经读过下面的下载管理器存在问题链接 android-chrome-browser-unnecessarily-renames-names-types-of-downloaded-files所以我试图通过使用以下方法将RequestHeader添加到DownloadManagerRequest来下载文件,但没有任何反应。请找到我的Downloader类的以下代码部分,请建议我使用DownloadManager从url下载文件的正确方法。

url:

  

HTTP:// 吸留 达网络/ 95 - **** / 95-3194.pdf AWSAccessKeyId = T9YG9HWQC1LHE5G5VF38&安培;过期= 1483443248&安培;签名= ž%2BkWzfEI2VawbCx%2F2Yto1kPcJKA%3D

由于

     public void download(Uri uri) {
                if (!isDownloading()) {
                    String fileName=getName(uri);
                    DownloadManager.Request request = new DownloadManager.Request(uri);
                    request.setTitle(fileName);
                    request.setNotificationVisibility(1);
                    request.allowScanningByMediaScanner();
                    request.addRequestHeader("Content-Type", "application/octet-stream");
                    request.addRequestHeader("Content-Disposition", "attachment; filename=\""+fileName.split("\\.")[0]+"."+fileName.split("\\.")[1].toUpperCase()+"\"");
                    String cookieContent = getCookieFromAppCookieManager(uri.getHost());
                    request.addRequestHeader("Cookie", cookieContent);
                    downloadId = downloadManager.enqueue(request);
                    register();
                }
            }

以下块返回文件名

 private String getName(Uri uri) {
        String name=uri.toString().split("jabord/")[1].split("\\?")[0];
        return name;
    }

返回appcookie经理

public String getCookieFromAppCookieManager(String url){
        android.webkit.CookieManager cookieManager = android.webkit.CookieManager.getInstance();
        if (cookieManager == null) {
            return null;
        }
        String rawCookieHeader = null;

        // Extract Set-Cookie header value from Android app CookieManager for this URL
        rawCookieHeader = cookieManager.getCookie(url);
        if (rawCookieHeader == null) {
            return null;
        }

        return rawCookieHeader;
    };

1 个答案:

答案 0 :(得分:2)

请删除标题并设置mimetype然后它将起作用。例如

 public void download(Uri uri) {
    if (!isDownloading()) {
        String fileName=getName(uri);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setTitle(fileName);
        request.setNotificationVisibility(1);
        request.allowScanningByMediaScanner();
        request.setMimeType("application/pdf");
        Log.e("Extension with ","UpperCase-->"+"\""+fileName.split("\\.")[0]+"."+fileName.split("\\.")[1].toUpperCase()+"\"");
        downloadId = downloadManager.enqueue(request);
        register();
    }
}