Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 +

like image 334
Cote Mounyo Avatar asked Aug 19 '13 21:08

Cote Mounyo


People also ask

How do you encode a space in Java?

Note that Java's URLEncoder class encodes space character( " " ) into a + sign. This is contrary to other languages like Javascript that encode space character into %20 .

Why is space %20 in URL?

Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

How do I encode a whitespace in a URL?

The reserved characters are different for each part. For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.


1 Answers

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.

like image 143
zapl Avatar answered Sep 30 '22 22:09

zapl