【问题标题】:How to use Android webview to download a text file如何使用 Android webview 下载文本文件
【发布时间】:2015-10-22 11:54:02
【问题描述】:

我很难让 android webview 从我的服务器应用程序下载文本文件。似乎它可能与传输协议或会话变量有关。使用 Web 浏览器应用程序时文件下载正常,但在我的自定义 webview 代码中不起作用。在我的自定义代码中,下载了一个文件,但它不是请求的文本文件。相反,它是登录屏幕的 HTML 代码。服务器导出器在执行导出之前检查用户是否已登录,如果没有则重定向到登录屏幕。

这里是 webview 下载器代码:

mWebView.setWebViewClient(new myWebClient());
mWebView.setDownloadListener(this);

@Override
public void onDownloadStart(String url, String userAgent,
        String contentDisposition, String mimetype, long contentLength) {

    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse(url));

    request.allowScanningByMediaScanner();

    // Notify client once download is completed!
    request.setNotificationVisibility(
            DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

    final String exportFileName = URLUtil.guessFileName(
                            url, contentDisposition, mimetype);
    request.setDestinationInExternalPublicDir(
            Environment.DIRECTORY_DOWNLOADS, exportFileName);

    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    dm.enqueue(request);
    // This is important!
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); 
    intent.addCategory(Intent.CATEGORY_OPENABLE); // CATEGORY.OPENABLE
    intent.setType("*/*");// any application,any extension
    Toast.makeText(getApplicationContext(), "Downloading File", 
            Toast.LENGTH_LONG).show();

}

在服务器端,这些是在生成文本文件之前使用的标头:

header("Content-Type: text/plain" );
header("Content-Disposition: attachment; filename=".$this->filename);

【问题讨论】:

  • 您的下载请求是否需要任何身份验证?您必须手动设置,例如新的 DownloadManager.Request 中的 cookie。
  • 是的,下载确实需要授权。可以使用更多关于需要做什么的指导。
  • 尤里卡,你的评论让我得到了这个答案:stackoverflow.com/questions/17929874/…
  • 很高兴给你一个有用的提示。您应该接受自己的答案,以将问题标记为已解决。

标签: android webview


【解决方案1】:

向新的 DownloadManager.Request 添加 cookie 解决了这个问题。

    String cookie = CookieManager.getInstance().getCookie(url);
    request.addRequestHeader("Cookie", cookie);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 2018-06-25
    相关资源
    最近更新 更多