Search code examples
androidurlurlencode

URL encoding in Android


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.


Solution

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

    • Java:

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

      val query: String = URLEncoder.encode("apples oranges", Charsets.UTF_8.name())
      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();