Search code examples
javaencodingjerseyuribuilder

Encoding issue with curly brackets and space in UriBuilder


I am using the com.sun.jersey.api.uri.UriBuilderImpl implementation of UriBuilder to encode a URL (version 1.19). The issue arises when the query parameter of my URL includes both curly brackets and a space.

Example:

UriBuilder uriBuilder = fromUri("www.something.com")
        .queryParam("q", "{some thing}");

return uriBuilder.build().toString();

This fails with:

javax.ws.rs.core.UriBuilderException: java.net.URISyntaxException: Illegal character in query at index 27: www.something.com?q=%7Bsome thing%7D

Which is interesting, as if I take the curly brackets away, I get the expected encoding: www.something.com?q=some+thing...

org.apache.http.client.utils.URIBuilder encodes that as I would expect, which is: www.something.com?q=%7Bsome+thing%7D

I've tried doing this:

...
.queryParam("q", UriComponent.encode(searchQuery, UriComponent.Type.QUERY_PARAM)).
.build();

But then the space character also gets encoded to www.something.com?q=%7Bsome%2Bthing%7D.

What do I have to do to get www.something.com?q=%7Bsome+thing%7D?


Solution

  • I'm using jersey-client v1.9.1 and your code run with no error.

    Here is my maven dependency:

    <!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->
            <dependency>
                <groupId>com.sun.jersey</groupId>
                <artifactId>jersey-client</artifactId>
                <version>1.9.1</version>
            </dependency>
    

    And the java code:

    import java.net.URI;
    
    import javax.ws.rs.core.UriBuilder;
    
    public class Main {
        public static void main(String[] args) throws Exception {
            try {
                URI url = UriBuilder.fromUri("www.something.com")
                        .queryParam("q", "{some thing}")
                        .build();
                System.out.println(url);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }
    

    The output: www.something.com?q=%7Bsome+thing%7D

    UPDATE

    The curly braces are the reason for failing with v1.19 (see the documentation)

    Here is a working version for v1.19:

            URI url = UriBuilder.fromPath("www.something.com")
                    .queryParam("q", "{value}")
                    .build("{some thing}", "value");
            System.out.println(url);