views:

191

answers:

1

How do you encode an url in Android? I thought it was like this:

final String encodedURL = URLEncoder.encode(urlAsString, "UTF-8");
URL url = new URL(encodedURL);

If I do the above, the http:// in urlAsString is replaced by http%3A%2F%2F in encodedURL and then I get a java.net.MalformedURLException when I use the url.

Thanks!

+2  A: 

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

String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;
alex
What if the whole url is unreliable? Should I encode everything except the protocol? I kind of expected a convenience method to do this.
hgpc
Then it's just a broken url. The idea is to prevent the query part from breaking the url.
alex
@hgpc - take a look at section 3 of RFC3986 (http://tools.ietf.org/html/rfc3986#section-3). It tells you how to encode the various portions of a URI. Unfortunately each portion of the URI (host, path, query, etc.) has slightly different encoding rules.
D.Shawley