how to url encode in android?

Viewed 70887
8 Answers

URLEncoder should be used only to encode queries, use java.net.URI class instead:

URI uri = new URI(
    "http",
    "www.theblacksheeponline.com", 
    "/party_img/thumbspps/912big_361999096_Flicking Off Douchebag.jpg",
    null);
String request = uri.toASCIIString();

I tried with URLEncoder that added (+) sign in replace of (" "), but it was not working and getting 404 url not found error.

Then i googled for get better answer and found this and its working awesome.

String urlStr = "http://www.example.com/test/file name.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();

This way of encoding url its very useful because using of URL we can separate url into different part. So, there is no need to perform any string operation.

Then second URI class, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.

Related