Android WebView - 下载PDF最终以HTML文件结束

时间:2014-11-09 21:34:17

标签: android webview download

我尝试从网页下载PDF文件。但是当我这样做时,我最终只得到一个HTML文件,因为登录不适合下载。

我尝试加载的链接看起来像这样:

https://somePage.de/auth/1%3A1%3A1026071014%3A3%3A0%3Aserv%3Ax/aufgaben/aufgabe3.pdf

已解决它应如下所示:

https://somePage.de/auth/1:1:1:122452345:4:4:serv:x/aufgaben/aufgabe3.pdf

下载由Downloadmanager完成:

@Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Toast.makeText(getActivity(), url, Toast.LENGTH_LONG).show();
            if (url.contains(".pdf")) {
                Request request = new Request(Uri.parse(url));
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(
                        Environment.DIRECTORY_DOWNLOADS, url.substring(url.lastIndexOf("/", url.length())));
                _DownloadManager.enqueue(request);

            } else
            view.loadUrl(url);

            return true;
        }

我想念这里的东西吗?也许在WebView中有某种配置?

1 个答案:

答案 0 :(得分:4)

好的,我终于找到了解决方案。问题是,下载管理器没有来自webview的登录状态。 解决方案是向您的cookie提出请求。这里的代码(仅两行):

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

    Toast.makeText(getActivity(), url, Toast.LENGTH_LONG).show();

    if (url.contains(".pdf")) {

        String cookie = CookieManager.getInstance().getCookie(url);
        Request request = new Request(Uri.parse(url));
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(
                Environment.DIRECTORY_DOWNLOADS, url.substring(url.lastIndexOf("/", url.length())));
        request.addRequestHeader("Cookie", cookie);
        _DownloadManager.enqueue(request);

    } else
        view.loadUrl(url);

    return true;
}