【问题标题】:Downloading file from webview returns HTML content not the actual file从 webview 下载文件返回 HTML 内容而不是实际文件
【发布时间】:2020-09-15 19:22:56
【问题描述】:

我正在使用 downloadListener 从 webview 下载文件。文件名被正确识别,但是 html 内容被下载。如果它是相关的,我正在尝试下载一个 .apk 文件。

      webView.setDownloadListener(new DownloadListener() {

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

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        InputStream is;
                        try {

                            final String filename= URLUtil.guessFileName(url, contentDisposition, mimetype);

                            Log.d("download","filename: "+filename);//filename is correct


                            URL u = new URL(url);
                            HttpURLConnection con = (HttpURLConnection) u.openConnection();
                            con.setRequestMethod("GET");
                            con.connect();
                            is = con.getInputStream();


                            // Path and File where to download the APK
                            File apk = new File(getFilesDir(),filename);
                            FileOutputStream output = new FileOutputStream(apk);

                            // Save file from URL
                            byte[] buffer = new byte[1024];
                            int len = 0;
                            long total=0;

                            while ((len = is.read(buffer)) != -1) {
                                output.write(buffer, 0, len);
                                total += len;
                            }

                            output.close();
                            is.close();

                        }
                        catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

【问题讨论】:

  • 这个问题可能很愚蠢,但url 是否指向正确的网址,您是否可以从该网址下载文件,例如curlwget
  • to download a file from a webview. ?从你的意思的服务器。或网站。
  • 发布 html 内容。查看html。它告诉你什么?您将使用重定向网址。
  • 在浏览器上下载工作绝对正常,文件也被正确识别,否则它不会返回它的名字。
  • @blackapps 在常规浏览器中,将下载文件并重定向 url。但是我不确定这是否会造成任何麻烦。

标签: java android webview download


【解决方案1】:

更新:解决方案是将 cookie 以及用户代理添加到请求属性中。

String cookie = CookieManager.getInstance().getCookie(url);
con.setRequestProperty("cookie",cookie);
con.setRequestProperty("User-Agent",userAgent);

【讨论】:

    猜你喜欢
    • 2014-10-06
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多