无法在网络视图中下载PDF

时间:2018-07-23 13:31:15

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

我正在尝试制作一个应用来下载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;
    }

1 个答案:

答案 0 :(得分:0)

//使用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();
    }

}

}