15

As the title says: which encoder would give me space as %20 as opposed to +? I need it for android. java.net.URLEncoder.encode gives +

Cote Mounyo
  • 13,817
  • 23
  • 66
  • 87

2 Answers2

26

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.

zapl
  • 63,179
  • 10
  • 123
  • 154
1

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

Community
  • 1
  • 1
zennon
  • 1,080
  • 10
  • 25