When downloading files from webview activity files always have 0 bytes

Viewed 125

I have an Android App with an Webview activity that shows some embedded reports. These can be exported in various formats (Excel, csv, pdf, text). The issue is that when I download these reports on my browser (or the chrome browser on my phone) they download fine. When I do it from the webview (same url) the files download but size is always 0 bytes.

Any ideas of what could be the reason for this?

Here is relevant code on the activity:

webView = findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient()
{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith(BackendConfig.URL_MOBILE_FINNISH)) {
            finish();
            Intent i = new Intent(WebViewActivity.this, BaseActivity.class);
            startActivity(i);
            return true;
        } else {
            webView.setDownloadListener(new DownloadListener() {
                public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                    DownloadManager.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.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype));
                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                    dm.enqueue(request);
                    Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
                }
            });
            return false;
        }
    }
});


WebSettings webSettings = webView.getSettings();

webSettings.setJavaScriptEnabled(true);
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setAllowFileAccess(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setDomStorageEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(false);
webSettings.setSupportZoom(false);
webSettings.setDefaultTextEncodingName("utf-8");
webView.addJavascriptInterface(new GetPassword(), "GetPassword");
webView.addJavascriptInterface(new GetSetupStatus(), "GetSetupStatus");
webView.loadUrl(startURL);
WebView.setWebContentsDebuggingEnabled(true);

I've been trying to sort this for weeks!

Thank you.

1 Answers

The 0 bytes issue can happen due to several factors and you will want to look around these areas to find the causing factor and fix this bug.

Use the downloading url and locate the html form via action attribute, if its method has POST then make sure when submit its triggered, the required input fields to fetch the file, if there is any are present in http request body. In some downloading mechanisms via JS, the file along its form input fields its populated and fetched in and from the DOM content thats created dynamically, and JS http downloading request uses data to request the file from such dynamically populated input fields, that will not be present to android webview download listener, which I suspect its your case given what you said.

Also, If the html form method its GET, then make sure all required queries are present in the downloading URL.

In some other instances where 0 bytes issue can happen, its that when you will have to make Jave native http connection request to the download url, with some missing body data or different http action method given its not possible via the webview download listener to customise the http request method as well as body data.

In more complex instances, 0 bytes can happen when you have server issues and it has nothing to do with android webview download listener such as if the data content length header its required by your web application or due to some issues with data compression which android webview cant handle and in such cases you might want to calculate the content length manually of the file and append to the http request headers, as well as disable compression for certain queries in urls or completely for your specific web application.

I hope this helps you in debugging.

Zakaria.

Related