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

  • Inserting a video into MediaStore
  • Is possible to set System DateTime from my Android App?
  • Allow unstable Android Gradle builds on Jenkins
  • Minimize activity on back key press
  • Find usage of id not working in Android Studio on Windows
  • Creating Android Location Object
  • Related posts:

    Programmatically Translate View Pre-Honeycomb
    Android WebView incorrectly handling newlines in preformatted text
    Native iOS/android application to Windows Phone
    How to set View alpha in lower Api than 11?
    Caching downloaded JSON data to SQLite database - is it a good idea?
    Why should a TypedArray be recycled?
  • Android - Blinking image using the Alpha fade animation
  • Firebase gets stuck on no INTERNET connection
  • Why does Android Lint warn about String.format using default locale when explicitly using Locale.US?
  • How to display static google map on android imageview?
  • How to give spacing between rating bar stars android?
  • How to set android show vertical orientation?
  • 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.