gpt4 book ai didi

java - 有什么方法可以使用 java.net.URI 在查询 arg 中发送 %2b(编码加号)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:29:45 25 4
gpt4 key购买 nike

我似乎找不到明确提及的内容,但如果您使用的是 java.net.URI,您似乎无法发送转义加号(“%2b”)作为查询参数值,因为查询参数被转义。

// bad: http://example.com/foo?a=%252b
new URI("http", null, "example.com", 80, "/foo", "a=%2b", null);

尝试了一个实际的“+”字符,但它按原样发送,因此服务器会将其解释为空格。

// bad: http://example.com/foo?a=+
new URI("http", null, "example.com", 80, "/foo", "a=+", null);

所以我猜你只需要自己对查询参数键和值进行百分比编码,并使用不会转义的单参数 URI 构造函数?也许让 URI 转义“路径”,因为规则很棘手(例如,“+”字符在路径中表示加号,而不是空格):

// good: http://example.com/foo?a=%2b
new URI(new URI("http", null, "example.com", 80, "/foo", null, null).toASCIIString() + "?a=%2b");

此外,文档声称您可以像这样创建一个 URI,它将与源 URI 相同:

URI u = ...;
URI identical = new URI(u.getScheme(),
u.getUserInfo(),
u.getPath(), u.getQuery(),
u.getFragment());

但是当它包含 %2b 时就不是这样了

URI u = new URI("http://example.com:80/foo?a=%2b");
URI identical = ...; // not identical! http://example.com:80/foo?a=+

令人沮丧,我想这就是为什么每个人都改用 apache commons 或 spring 类的原因吧?

附言:http://docs.oracle.com/javase/6/docs/api/java/net/URI.html引用了“以下身份也持有”部分中不存在的 URI 构造函数。它需要删除“authority”参数。

最佳答案

我遇到了同样的麻烦。经过一些研究,我认为如果你需要加号的 %2b 编码,最好不要使用 URI 类作为结果。我正在使用这样的代码:

URI uri = new URI(...);
String asciiUrl = uri.toASCIIString();
String plusReplaced = asciiUrl.replace("+", "%2b");

关于java - 有什么方法可以使用 java.net.URI 在查询 arg 中发送 %2b(编码加号)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14526320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com