Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebView - can't download file without requesting it twice?

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?

like image 786
Eli Revah Avatar asked Aug 03 '12 19:08

Eli Revah


2 Answers

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.

like image 64
AJMansfield Avatar answered Nov 08 '22 15:11

AJMansfield


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;
}
like image 28
ceptno Avatar answered Nov 08 '22 15:11

ceptno