【问题标题】:Unable to download a pdf in a webview无法在 web 视图中下载 pdf
【发布时间】:2018-12-30 23:31:39
【问题描述】:

我正在尝试制作一个应用程序来下载 pdf(银行对账单/Aadhar),但无法这样做,而我能够下载其他文件,如虚拟 pdf,但不能从银行或 Aadhar 网站下载。当我点击 pdf 下载按钮 onPagestarted() 时,我得到了一个带有 .jsp 的链接 我得到的链接是when i click pdf download button

我也设置了下载管理器,但从来没有被调用过

我的代码

  webView.setWebViewClient(new MyWebClient(this,url));
    webView.setWebChromeClient(new MyWebChromeClient(this));

    webView.getSettings().setJavaScriptEnabled(true);
    webView.addJavascriptInterface(new WebAppInterface(context,this), "Android");

    webView.setDownloadListener((url, userAgent, contentDisposition, mimeType, contentLength) -> {
        webView.loadUrl(WebAppInterface.getBase64StringFromBlobUrl(url));

        Log.e("BrowserActivity",url);
        Log.e("download", url);
        DownloadManager.Request request;
        request = new DownloadManager.Request(Uri.parse(url));
        request.setMimeType(mimeType);
        //------------------------COOKIE!!------------------------
        String cookies = CookieManager.getInstance().getCookie(url);
        request.addRequestHeader("cookie", cookies);
        //------------------------COOKIE!!------------------------
        request.addRequestHeader("User-Agent", userAgent);
        request.setDescription("Downloading file...");
        request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalFilesDir(this, path, URLUtil.guessFileName(url, contentDisposition, mimeType));
        dm = (DownloadManager) this.getSystemService(DOWNLOAD_SERVICE);
        dm.enqueue(request);
       createPdf(URLUtil.guessFileName(url,contentDisposition,mimeType));  });

 webView.getSettings().setAppCachePath(context.getApplicationContext().getCacheDir().getAbsolutePath());
    webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);

    webView.requestFocus(View.FOCUS_DOWN);

    webView.getSettings().setSupportMultipleWindows(true);
    webView.getSettings()
            .setJavaScriptCanOpenWindowsAutomatically(true);
    webView.getSettings().setDomStorageEnabled(true);

    webView.getSettings().setBuiltInZoomControls(true);

    webView.getSettings().setDisplayZoomControls(false);
    webView.getSettings().setAllowContentAccess(true);
    webView.getSettings().setDatabaseEnabled(true);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        webView.getSettings().setSafeBrowsingEnabled(true);
    }



    webView.loadUrl(url);

WebViewClient 的代码是

 class MyWebClient extends WebViewClient {
    Context context;
    String url1;

    public MyWebClient(Context context,String url) {
        super();
        this.context = context;
        this.url1=url;
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        /**
         * Check for the url, if the url is from same domain
         * open the url in the same activity as new intent
         * else pass the url to browser activity
         * */

        return super.shouldOverrideUrlLoading(view, url);
    }


    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);

        isWebPageLoaded = false;
    }

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

        isWebPageLoaded = true;
    }

【问题讨论】:

  • 不清楚你想要什么。并且 webview 无法显示 pdf 开头。
  • @greenapps 我想在 webView 的帮助下下载银行对账单,但我的代码无法从任何虚拟 pdf 链接下载其他 pdf 文件
  • @greenapps 请建议
  • 你找到解决办法了吗?

标签: android webview android-webview android-download-manager


【解决方案1】:

// 使用 Asyntask 从 url 下载 pdf,如下所示

public class MainActivity extends ActionBarActivity {

private ProgressDialog pDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new DownloadFileFromURL().execute("http://www.example.com/something.pdf");
}




class DownloadFileFromURL extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        System.out.println("Starting download");

        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Loading... Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            String root = Environment.getExternalStorageDirectory().toString();

            System.out.println("Downloading");
            URL url = new URL(f_url[0]);

            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream to write file

            OutputStream output = new FileOutputStream(root+"/downloadedfile.pdf");
            byte data[] = new byte[1024];

            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;

                // writing data to file
                output.write(data, 0, count);

            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }



    /**
     * After completing background task
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        System.out.println("Downloaded");

        pDialog.dismiss();
    }

}

}

【讨论】:

  • 不知道它可以与当前的任何扩展名一起使用的 URL,它显示 .jsp。所以什么时候开始这个异步是不可预测的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-27
  • 2015-10-06
  • 2012-09-15
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 2020-08-12
相关资源
最近更新 更多