Search code examples
javaurlencodejersey-2.0url-encodingjersey-client

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".


Solution

  • When you create a parameter with a value in curly, Jersey thinks you want to use a URL parameter. See https://jersey.github.io/documentation/latest/uris-and-links.html.

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

    So you should encode curly braces yourselves via URLEncoder, probably as described there: How to force URIBuilder.path(...) to encode parameters like "%AD"? This method doesn't always encode parameters with percentage, correctly.