1
votes

In my app, there is an ImageView that display an image from a URL.

I download the image using this method:

        Bitmap bitmap=null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;

This works only with URLs that has numbers or english letters and doesn't work with any other chars (like spaces):

Good URL: http://site.com/images/image.png

Bad URL: http://site.com/images/image 1.png

I tried to chage the URL encoding (URLEncoder.encode), but it changes the whole URL (incliding slashes, ect...).

Do I need to replace some chars after the encoding? or maybe there is a better way?

Thanks :)

1

1 Answers

4
votes

"Url encoding in Android"

You don't encode the entire URL, only parts of it that come from "unreliable sources". -yanchenko

String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "https://stackoverflow.com/search?q=" + query;

This is fine if you are just dealing with a specific part of a URL and you know how to construct or reconstruct the URL. For a more general approach which can handle any url string, see my answer below. – Craig B

String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();