If I listen with DownloadListener
, I get the URL which I need to request after the browser already requested it. The browser already opened a connection to the URL (which is how it knows this is a download), why can't it pass me the connection?
I also tried to assign a custom WebViewClient
to the WebView
and use shouldOverrideUrlLoading
to catch URLs before they are requested. To download files that way, I request every URL before the browser and by it's Content-Type I decide whether to download it or not, if it is then I download it from the already-opened connection, otherwise I close the connection and instruct the browser to load it, and the browser... requests it again. Plus, in shouldOverrideUrlLoading
I'm not told which method and what cookies should I use to request the given URL.
How can I not unnecessarily request twice and still be able to download files with WebView?
A simple solution is modify it to just download it without asking the user for confirmation based on content type, but instead just put a cancel button on whatever is used to monitor the download.
Why not just use the url to download it using outputstream? Here is an example:
private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
Are you sure you wish to interrupt browser work? It use multy-thread to download multiple URL's and also he is managing his own file system to create cookies for that urls and he know when he need to delete them and update them.
So are you sure?