Is it true that the WebView will perform an Http Get and download the complete file then it calls calls my onDownloadStart() method and my code downloads the file again?
In a WebView used in an Android application we need to handle downloading a PDF file. I'm seeing behavior which I guess makes sense, but it seems odd so I'm hoping someone can verify for me.
When the WebView is set up we call setDownloadListener() and create a new DownloadListener to handle the onDownloadStart() method call. In the onDownloadStart() method we use an HttpURLConnection to get the resource from our web server.
In network traces I see two Http Get requests performed for the same resource. I assume this is because the webview first does a Get on the resource, then the webview does its own processing and determines that it cannot render the resource. The webview then calls the onDownloadStart() method and we retrieve the resource a second time.
The docs for SetDownloadListener say:
Register the interface to be used when content can not be handled by the rendering engine, and should be downloaded instead. This will replace the current handler.
The webview would not know if it can render the resource until it gets a response from the server and can read the content-type returned. So, it must first do a GET or a HEAD to read the response headers. So, the double download behavior seems to make sense.
And, some follow up questions:
- Is this a common situation? Do most apps that download files from within a webview really download the file twice? (that seems expensive but I think it may be happening)
- Is there a way to reuse the already downloaded content from the first request rather than requesting it again?
- Why doesn't the WebView use the Http HEAD method on the first request rather than GET? (I guess this would make every hyperlink a two step process and that would be expensive too)
- Is there a way I can prevent the extra download? Perhaps using shouldOverrideUrlLoading() to intercept the request?