Jos*_*nez 4 java urlencode url-encoding jersey-client jersey-2.0
我们正在使用Jersey Client 2.21。我注意到,当我们将花括号(也称为花括号)作为参数值时,则无法正确编码。不仅如此,大括号内的所有内容均未得到编码。对于常规括号或我测试过的其他不安全字符,情况并非如此。
请参见下面的示例。在此示例中,我输入三个参数。仅带有空格的控制参数。一种带花括号,另一种带方括号。
public static void testJerseyEncoding() {
Client client = ClientBuilder.newClient();
String url = "http://foo.com/path";
Map<String, String> map = new HashMap<>();
map.put("paramWithCurly", " {with a space}");
map.put("paramWithOutCurly", "with a space");
map.put("paramWithBracket", "[with a space]");
WebTarget target = client.target(url);
for (Map.Entry<String, String> entry : map.entrySet()) {
target = target.queryParam(entry.getKey(), entry.getValue());
}
System.out.println(target.toString());
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
JerseyWebTarget { http://foo.com/path?paramWithBracket=%5Bwith+a+space%5D¶mWithOutCurly=with+a+space¶mWithCurly=+{with a space} }
Run Code Online (Sandbox Code Playgroud)
泽西客户有问题吗?还是我错过了什么?花括号应已编码为“%7B”。
小智 7
不用手动预编码的查询参数值,更好的方法可能会做总是使用模板参数,然后使用resolveTemplate()与联合国安全值。
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://server")
.path("/foo")
.queryParam("bar", "{bar}")
.resolveTemplate("bar", "{\"foo\":\"bar\"}");
assertThat(target.getUri().toString())
.isEqualTo("http://server/foo?bar=%7B%22foo%22%3A%22bar%22%7D");
Run Code Online (Sandbox Code Playgroud)
所以,首先,泽西岛默认做模板是很疯狂的。其次,这里的所有解决方案都是错误的......URLEncoder.encode(..., "UTF-8")对包含空格的查询参数不起作用。由于 URLEncoder 会将空格编码为+,而 Jersey 会将其解释为加号,因此 Jersey 最终将其编码为%2B. 看https://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html以供参考。
我提出的解决方案,我不是很满意(总是与Java)是更换所有{和}使用%7B,并%7D分别如下:
Map<String, String> map = new HashMap<>();
map.put("paramWithCurly", " {with a space}".replaceAll("\\{", "%7B").replaceAll("\\}", "%7D"));
map.put("paramWithOutCurly", "with a space");
map.put("paramWithBracket", "[with a space]");
WebTarget target = client.target(url);
for (Map.Entry<String, String> entry : map.entrySet()) {
target = target.queryParam(entry.getKey(), entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)
当您创建带有 curly 值的参数时,Jersey 认为您想要使用 URL 参数。请参阅https://jersey.github.io/documentation/latest/uris-and-links.html。
UriBuilder.fromUri("http://localhost/")
.path("{a}")
.queryParam("name", "{value}")
.build("segment", "value");
Run Code Online (Sandbox Code Playgroud)
因此,您应该通过 URLEncoder 自己对大括号进行编码,可能如下所述:如何强制 URIBuilder.path(...) 对像“%AD”这样的参数进行编码?此方法并不总是正确地用百分比对参数进行编码。
| 归档时间: |
|
| 查看次数: |
3162 次 |
| 最近记录: |