首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在泽西客户端2中编码花括号

问在泽西客户端2中编码花括号
EN

Stack Overflow用户
提问于 2016-02-26 18:38:44
回答 5查看 5.9K关注 0票数 6

我们使用的是泽西客户端2.21。我注意到,当我们将大括号(也称为花括号)作为param值时,它没有得到正确的编码。不仅如此,大括号内的任何东西也不会被编码。对于我测试过的常规括号或其他不安全字符,情况并非如此。

请参阅下面的例子。在本例中,我输入了三个参数。只有空格的控制参数。一个带花括号,一个有规则的括号。

代码语言:javascript
复制
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());
}

这是输出:

代码语言:javascript
复制
JerseyWebTarget { http://foo.com/path?paramWithBracket=%5Bwith+a+space%5D&paramWithOutCurly=with+a+space&paramWithCurly=+{with a space} }

是泽西的客户出了什么问题还是我漏掉了什么?花括号应该编码为"%7B“。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-02-26 18:48:33

当您创建一个值为curly的参数时,泽西岛认为您希望使用URL参数。见https://jersey.github.io/documentation/latest/uris-and-links.html。

代码语言:javascript
复制
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。

票数 2
EN

Stack Overflow用户

发布于 2017-09-12 23:59:55

与手动对查询参数值进行预编码不同,更好的方法可能是始终使用模板参数,然后将resolveTemplate()与不安全值一起使用。

代码语言:javascript
复制
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");
票数 9
EN

Stack Overflow用户

发布于 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,如下所示:

代码语言:javascript
复制
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());
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35659273

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档