Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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 +

share|improve this question

marked as duplicate by Ted Hopp, morgano, laalto, Shankar Damodaran, Charles Caldwell Aug 20 at 17:14

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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

share|improve this answer

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

share|improve this answer

As mentioned here, you could just replace the string yourself using

String temp = "a+url+with+plus+signs";

temp = temp.replaceAll("+", "%20");
URL sourceUrl = new URL(temp);
share|improve this answer
 
This is wrong. Other special characters present in the text may also need to be escaped. If you escape the space characters first like that and then use URLEncoder.encode, the % in %20 will itself be encoded as %25. If you don't use URLEncoder.encode, then you risk other special characters remaining in the text. Much better to encode first and then replace the + with %20. –  Ted Hopp Aug 19 at 21:26
 
Good point. I will update my answer. –  Adam Johns Aug 19 at 21:29
 
You probably should just use temp.replace("+", "%20"); replaceAll expects a regex as the first parameter and the + would need to be escaped as "\\+". –  Ted Hopp Aug 19 at 21:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.