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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:30:19  来源:igfitidea点击:

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

javaandroidurlencodeurl-encoding

提问by Cote Mounyo

As the title says: which encoder would give me space as %20as 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:

更多信息请看这篇文章:

URLEncoder not able to translate space character

URLEncoder 无法翻译空格字符

回答by zapl

Android has it's own Uriclass 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

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