How do you encode a 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.
I'm going to add one suggestion here. You can do this which avoids having to get any external libraries.
Give this a try:
You can see that in this particular URL, I need to have those spaces encoded so that I can use it for a request.
This takes advantage of a couple features available to you in Android classes. First, the URL class can break a url into its proper components so there is no need for you to do any string search/replace work. Secondly, 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.
The beauty of this approach is that you can take any valid url string and have it work without needing any special knowledge of it yourself.
you can use below methods
or
the second one is better than first.
For android, I would use String android.net.Uri.encode(String s)
Ex/
Also you can use this
it's the most simple method
You don't encode the entire URL, only parts of it that come from "unreliable sources".
Alternatively, you can use Strings.urlEncode(String str) of DroidParts that doesn't throw checked exceptions.
Or use something like