Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding curly braces in Jersey Client 2

We are using Jersey Client 2.21. I am noticing that when we put curly braces (aka curly brackets) as a param value, then it does not get properly encoded. Not only that, but anything inside the curly braces does not get encoded either. This is not true for regular brackets or other unsafe characters that I have tested with.

Please see the example below. In this example I enter three params. A control param with just spaces. One with curly braces, and one with regular brackets.

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());
}

Here is the output:

JerseyWebTarget { http://foo.com/path?paramWithBracket=%5Bwith+a+space%5D&paramWithOutCurly=with+a+space&paramWithCurly=+{with a space} }

Is something broken with the Jersey Client or am I missing something? The curly braces should have been encoded to "%7B".

like image 305
Jose Martinez Avatar asked Feb 26 '16 18:02

Jose Martinez


Video Answer


1 Answers

Instead of manually pre-encoding the query parameter value, a better way might be do always use a template parameter and then use resolveTemplate() with the un-safe value.

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");
like image 178
headexplodes Avatar answered Sep 22 '22 22:09

headexplodes