是否可以在Android DownloadManager中提交cookie

时间:2012-06-07 21:34:51

标签: android cookies download

我正在使用android DownloadManager API从我学校的服务器下载文件。我有权使用登录访问这些文件,但我无法弄清楚如何使用我的DownloadManager.Request提交cookie下载代码如下。 dm是全局DownloadManagerurl是一个php下载脚本,可重定向到文件,通常是pdf / doc /等。

dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(Uri.parse(url));
dm.enqueue(request);

Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);

这很好,但是我下载了一个html文件,这是我学校网站的登录页面。显然我需要以某种方式提交用户的会话cookie,但我在文档中看不到这样做的任何方式。

2 个答案:

答案 0 :(得分:22)

Cookie通过HTTP标头发送(命名,足够恰当,“Cookie”),幸运的是,DownloadManager.Request has a method添加自己的标头。

所以你想要做的就是这样:

Request request = new Request(Uri.parse(url)); 
request.addRequestHeader("Cookie", "contents");
dm.enqueue(request);

当然,您必须将“内容”替换为实际的Cookie内容。 CookieManager类对于获取站点的当前cookie非常有用,但如果失败,则另一个选择是让您的应用程序发出登录请求并获取返回的cookie。

答案 1 :(得分:1)

您可以使用CookieManager检索Cookie,如下所示(我使用过webview):

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            String cookieString = CookieManager.getInstance().getCookie(url);

        }
    });

    //Enable Javascript
    webView.getSettings().setJavaScriptEnabled(true);
    //Clear All and load url
    webView.loadUrl(URL_TO_SERVE);

然后将其传递给DownloadManager:

  //Create a DownloadManager.Request with all the information necessary to start the download
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url))
            .setTitle("File")// Title of the Download Notification
            .setDescription("Downloading")// Description of the Download Notification
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)// Visibility of the download Notification
            .setDestinationUri(Uri.fromFile(file))// Uri of the destination file
            .setAllowedOverMetered(true)// Set if download is allowed on Mobile network
            .setAllowedOverRoaming(true);
    request.addRequestHeader("cookie", cookieString);
    /*request.addRequestHeader("User-Agent", cookieString);*/
    DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    downloadID = downloadManager.enqueue(request);// enqueue puts the download request in the queue.
相关问题