Search code examples
androidcookiesandroid-webviewandroid-download-manager

Android DownloadManager doesn't save file


I am having problems with Android's DownloadManager and a WebView. There are a couple of links that return a generated file for the current user (PDF, etc.). These links only work for logged in user, so I am passing the authentication cookie to the DownloadManager. I can see from the server logs that this works correctly: all the hits to the download URL are done with the application cookie, the server is accepting this and is generating the correct file for the correct user. However all entries in the download manager are listed as unsuccessful.

I guess there is something trivial that I am missing here, but I have just started with Android and am not seeing it.

Here is part of the code for the MainActivity:

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.setDownloadListener(new DownloadListener() {
    public void onDownloadStart(String url,
                                String userAgent,
                                String contentDisposition,
                                String mimetype,
                                long contentLength) {
                                    String cookie = CookieManager.getInstance().getCookie(url);
                                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                    Request request = new Request(Uri.parse(url));
                                    request.addRequestHeader("Cookie", cookie);
                                    dm.enqueue(request);
                                }
    });

How can I make the download manager download the generated files?


Solution

  • After some more work on this, I found the problem: it seems android's DownloadManager needs the Content-Length header present on the response, something I wasn't sending for my generated files.