java.net.URLEncoder.encode encodes space as + but I need %20

This question already has an answer here:

  • URLEncoder not able to translate space character

    11 answers

  • How to apply custom image to checkbox in android
  • Best way to implement Socket.io in android
  • Multiple dex files define Lcom/google/firebase/FirebaseException
  • java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState with DialogFragment
  • Android fill percent of layout
  • Google+ sign out from a different activity
  • Set Key and Value in spinner
  • Android Webview: “Uncaught TypeError: Cannot read property 'getItem' of null”
  • Android one OnClick method for multiple buttons?
  • How To Test BOOT_COMPLETED Broadcast Receiver In Emulator
  • phonegap build not showing splashscreen
  • DialogFragment and force to show keyboard
  • 2 Solutions collect form web for “java.net.URLEncoder.encode encodes space as + but I need %20”

    Android has it’s own Uri class which you could use.

    E.g.

    String url = Uri.parse("http://www.google.com").buildUpon()
        .appendQueryParameter("q", "foo bar")
        .appendQueryParameter("xml", "<Hellö>")
        .build().toString();
    

    results in

    http://www.google.com?q=foo%20bar&xml=%3CHell%C3%B6%3E

    Uri 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.

    Note: only _-.* are considered unreserved characters by URLEncoder. !~'() would get converted to %21%7E%27%28%29.

    You have to replace the + by yourself.

    Example:

    System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20"));
    

    For more look at this post:

    URLEncoder not able to translate space character

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.