java.net.URLEncoder.encode将空间编码为+但我需要%20

时间:2013-08-19 21:17:47

标签: java android urlencode url-encoding

正如标题所说:哪个编码器会给我%20而不是+的空格?我需要它为Android。 java.net.URLEncoder.encode给出了+

2 个答案:

答案 0 :(得分:25)

Android拥有您可以使用的自己的Uri课程。

E.g。

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

结果

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

  

Uri将给定字符串中的字符编码为'%' - 使用UTF-8方案转义八位字节。保留字母(“A-Z”,“a-z”),数字(“0-9”)和未保留字符(“_-!。〜'()*”)。

注意:_-.*仅将URLEncoder视为未保留的字符。 !~'()会转换为%21%7E%27%28%29

答案 1 :(得分:2)

您必须自己替换+

示例:

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

更多关注这篇文章:

URLEncoder not able to translate space character