2016-02-26 24 views
2

我們使用的是澤西客戶端2.21。我注意到,當我們將大括號(又名花括號)作爲參數值時,它不會得到正確的編碼。不僅如此,而且大括號內的任何內容都不會被編碼。對於我測試過的常規括號或其他不安全字符,這不是真的。在澤西客戶端2編碼大括號2

請看下面的例子。在這個例子中,我輸入了三個參數。一個只有空格的控制參數。一個花括號,另一個花括號。

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&paramWithOutCurly=with+a+space&paramWithCurly=+{with a space} } 

有什麼事與Jersey客戶端破還是我失去了一些東西?花括號應該被編碼爲「%7B」。

回答

0

當您使用捲曲值創建參數時,Jersey認爲您想使用URL參數。見https://jersey.java.net/documentation/latest/uris-and-links.htmlHow to force URIBuilder.path(...) to encode parameters like "%AD"? This method doesn't always encode parameters with percentage, correctly

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

所以,你應該與那裏描述通過類URLEncoder編碼大括號自己,大概。

+2

謝謝你發現它爲什麼不編碼大括號的奧祕。任何想法如何關閉這個花括號「功能」?對於球衣客戶端框架來說,處理花括號的方式看起來不太合適,花括號可編碼,因此可能會顯示在URI中。 –

3

而不是手動預編碼查詢參數值,更好的方法可能是總是使用模板參數,然後使用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");