Take the 2-minute tour ×

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();
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        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 :)

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

"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 = "http://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();
share|improve this answer
Thanks! :) but there is still a little problem: it doesn't work with hebrew chars. What should I do? –  eviabs Nov 10 '12 at 17:50
I think you need to encode the Hebrew character part explicitly using URLEncoder. Seems only few non-ASCII characters are taken care by URI, check "Encoding and Decoding URI Components" section in here and also check this link –  1O1 Nov 10 '12 at 18:27
are you using a URL or a IRI (Internationalized Resource Identifier)? –  1O1 Nov 10 '12 at 18:47
There are hebrew chars in it (site.com/imagesעברית.png), so it's IRI, isn't it? I'm a bit confused right now... –  eviabs Nov 10 '12 at 18:52
Its an IRI, so you need to follow this link. Also its mentioned in android doc: A URI's host, port and scheme are not eligible for encoding and must not contain illegal characters. So take the part which is hebrew and encode it before constructing an URI. –  1O1 Nov 10 '12 at 19:37
show 2 more comments

Your Answer


