我们使用的是泽西客户端2.21。我注意到,当我们将大括号(也称为花括号)作为param值时,它没有得到正确的编码。不仅如此,大括号内的任何东西也不会被编码。对于我测试过的常规括号或其他不安全字符,情况并非如此。
请参阅下面的例子。在本例中,我输入了三个参数。只有空格的控制参数。一个带花括号,一个有规则的括号。
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());
}这是输出:
JerseyWebTarget { http://foo.com/path?paramWithBracket=%5Bwith+a+space%5D¶mWithOutCurly=with+a+space¶mWithCurly=+{with a space} }是泽西的客户出了什么问题还是我漏掉了什么?花括号应该编码为"%7B“。
发布于 2016-02-26 18:48:33
当您创建一个值为curly的参数时,泽西岛认为您希望使用URL参数。见https://jersey.github.io/documentation/latest/uris-and-links.html。
UriBuilder.fromUri("http://localhost/")
.path("{a}")
.queryParam("name", "{value}")
.build("segment", "value");因此,您应该通过URLEncoder对自己进行大括号编码,可能就像在这里描述的那样:How to force URIBuilder.path(...) to encode parameters like "%AD"? This method doesn't always encode parameters with percentage, correctly。
发布于 2017-09-12 23:59:55
与手动对查询参数值进行预编码不同,更好的方法可能是始终使用模板参数,然后将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");发布于 2018-10-25 13:00:29
所以,首先,泽西岛在默认情况下做模板是很疯狂的。其次,这里的所有解决方案都是wrong...doing URLEncoder.encode(..., "UTF-8"),它不适用于包含空格的查询参数。由于URLEncoder将空间编码为+,而泽西将其解释为加号,因此泽西岛最终将其编码为%2B。参考见https://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html。
我提议的解决方案(与以往一样,我对此并不满意)是将所有{和}分别替换为%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());
}https://stackoverflow.com/questions/35659273
复制相似问题