java.net.URLEncoder.encode 将空格编码为 + 但我需要 %20
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18323292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.net.URLEncoder.encode encodes space as + but I need %20
提问by Cote Mounyo
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 +
正如标题所说:哪个编码器会给我空间%20
而不是+
?我需要它用于安卓。java.net.URLEncoder.encode 给出+
回答by zennon
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:
更多信息请看这篇文章:
回答by zapl
Android has it's own Uri
class which you could use.
Android 有它自己的Uri
类,您可以使用它。
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
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.
Uri
使用 UTF-8 方案将给定字符串中的字符编码为 '%' 转义八位字节。保持字母(“AZ”、“az”)、数字(“0-9”)和非保留字符(“_-!.~'()*”)不变。
Note: only _-.*
are considered unreserved characters by URLEncoder
. !~'()
would get converted to %21%7E%27%28%29
.
注意:仅_-.*
被 视为非保留字符URLEncoder
。!~'()
将被转换为%21%7E%27%28%29
.