在Jersey Client 2中编码花括号

我们正在使用Jersey Client 2.21。 我注意到,当我们将花括号(又名花括号)作为参数值时,它不会被正确编码。 不仅如此,花括号内的任何内容都不会被编码。 对于我测试过的常规括号或其他不安全字符,情况并非如此。

请参阅下面的示例。 在这个例子中,我输入三个参数。 一个只有空格的控制参数。 一个用花括号,一个用常规括号。

public static void testJerseyEncoding() { Client client = ClientBuilder.newClient(); String url = "http://foo.com/path"; Map 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 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&paramWithOutCurly=with+a+space&paramWithCurly=+{with a space} } 

泽西客户端有什么问题,或者我错过了什么? 花括号应编码为“%7B”。

当您使用curl值创建参数时,Jersey认为您要使用URL参数。 请参阅https://jersey.java.net/documentation/latest/uris-and-links.html 。

 UriBuilder.fromUri("http://localhost/") .path("{a}") .queryParam("name", "{value}") .build("segment", "value"); 

所以你应该通过URLEncoder自己编码花括号,可能就像那里描述的那样: 如何强制URIBuilder.path(…)编码像“%AD”这样的参数? 此方法并不总是正确地使用百分比编码参数 。

不是手动预编码查询参数值,更好的方法可能是始终使用模板参数,然后使用带有不安全值的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"); 

您可以使用URLEncoder.encode(“…”,“UTF-8”)方法解决此问题

String java.net.URLEncoder.encode(String s,String enc)throws UnsupportedEncodingException

使用特定的编码方案将字符串转换为application / x-www-form-urlencoded格式。 此方法使用提供的编码方案来获取不安全字符的字节。

使用URLEncoder.encode更新代码

  try { map.put("paramWithCurly", URLEncoder.encode(" {with a space}", "UTF-8")); map.put("paramWithOutCurly", URLEncoder.encode("with a space", "UTF-8")); map.put("paramWithBracket", URLEncoder.encode("[with a space]", "UTF-8")); } catch (UnsupportedEncodingException e1) { System.err.println("........"); } 

这是输出:

 JerseyWebTarget { http://foo.com/path?paramWithBracket=%5Bwith%2Ba%2Bspace%5D&paramWithOutCurly=with%2Ba%2Bspace&paramWithCurly=%2B%7Bwith%2Ba%2Bspace%7D } 

暗示:-

 using UTF-8 as the encoding scheme the string "The string ü@foo-bar" would get converted to "The+string+%C3%BC%40foo-bar" 

参考: https //stackoverflow.com/a/607403/6638958