Question

My function intercepts all the request done to the webview. Like load a page.

@Override
public WebResourceResponse shouldInterceptRequest(final WebView view,
    String url) {...}

All the html, css and js files are answered correctly, but when I want to send a png or gif image as response, it does not work. They probably need special MIME types but I can't make it work.

Have to say that the images I want to send are received with a HttpURLConnection in an InputStream and converted to String, and saved in a folder; so when I need the image, I just take that file (a String) and convert it to InputStream.

InputStream is = new ByteArrayInputStream(imageString.getBytes());
return new WebResourceResponse("text/html", "UTF-8", is);

I tried with image/gif, image/png and nothing works.

Any ideas?

Était-ce utile?

La solution

The output stream needs to be FileOutputStream's

You need to save the image in byte format, no encoding needed.

Keep in mind that the you need to keep the image file extention. For example if you're downloading image.png and saving it as image.tiff it will not work.

This is how I would download an image:

URLConnection conn;

BufferedInputStream bistream = null;
BufferedOutputStream bostream = null;

boolean failed = false;

try
{
    conn = new URL("http://../image.png").openConnection();

    bistream = new BufferedInputStream(conn.getInputStream(), 512);

    byte[] b = new byte[512];

    int len = -1;

    bostream = 
        new BufferedOutputStream(
            new FileOutputStream(new File("/../image-downloaded.png")));

    while((len = bistream.read(b)) != -1)
    {
        bostream.write(b, 0, len);
    }
}
catch(Exception e) // poor practice, catch each exception separately.
{                   /* MalformedURLException -> IOException -> Exception */
    e.printStackTrace();

    failed = true;
}
finally
{
    if(bostream != null)
    {
        try
        {
            bostream.flush();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bostream.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    if(bistream != null)
    {
        try
        {
            bistream.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

if(failed == false)
{
    //code
}
else
{
    // code
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top