URL encoding in Android

AndroidUrlUrlencode

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

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

  • Java:

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

    val query: String = URLEncoder.encode("apples oranges", "utf-8")
    val url = "http://stackoverflow.com/search?q=$query"
    

Alternatively, you can use Strings.urlEncode(String str) of DroidParts that doesn't throw checked exceptions.

Or use something like

String uri = Uri.parse("http://...")
                .buildUpon()
                .appendQueryParameter("key", "val")
                .build().toString();

Solution 2 - Android

I'm going to add one suggestion here. You can do this which avoids having to get any external libraries.

Give this a try:

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();

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.

Solution 3 - Android

For android, I would use String android.net.Uri.encode(String s)

> Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes all other characters.

Ex/

String urlEncoded = "http://stackoverflow.com/search?q=" + Uri.encode(query);

Solution 4 - Android

Also you can use this

private static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);

it's the most simple method

Solution 5 - Android

try {
					query = URLEncoder.encode(query, "utf-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

Solution 6 - Android

you can use below methods

public static String parseUrl(String surl) throws Exception
{
	URL u = new URL(surl);
	return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();
}

or

public String parseURL(String url, Map<String, String> params)
{
	Builder builder = Uri.parse(url).buildUpon();
	for (String key : params.keySet())
	{
		builder.appendQueryParameter(key, params.get(key));
	}
	return builder.build().toString();
}

the second one is better than first.

Solution 7 - Android

Find Arabic chars and replace them with its UTF-8 encoding. some thing like this:

for (int i = 0; i < urlAsString.length(); i++) {
	if (urlAsString.charAt(i) > 255) {
		urlAsString = urlAsString.substring(0, i) + URLEncoder.encode(urlAsString.charAt(i)+"", "UTF-8") + urlAsString.substring(i+1);
	}
}
encodedURL = urlAsString;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhpiqueView Question on Stackoverflow
Solution 1 - AndroidyanchenkoView Answer on Stackoverflow
Solution 2 - AndroidCraig BView Answer on Stackoverflow
Solution 3 - AndroidtanutapiView Answer on Stackoverflow
Solution 4 - AndroidJedoView Answer on Stackoverflow
Solution 5 - AndroidThiagoView Answer on Stackoverflow
Solution 6 - AndroidElangoView Answer on Stackoverflow
Solution 7 - AndroidAli JafariView Answer on Stackoverflow