Search code examples
java-8jersey-2.0jersey-client

Adding query parms to WebTarget with Jersey Client 2.x


I'm trying to add query params to WebTarget of Jax-RS(Jersey Client 2.x) as below

public WebTarget webTarget(String path, Map<String, String> queryMap) {

        WebTarget webTarget = client.target(this.address.getUrl()).path(path);
        if (queryMap != null)
            queryMap.entrySet().forEach(e -> webTarget.queryParam(e.getKey(), e.getValue()));
        return webTarget;

}

The issue is WebTarget is immutable and returns new WebTarget every time .queryParam() is invoked, but cannot use mutable variables inside the lambda expression to reassign the WebTarget to be used within the forEach(), how do I capture the immutable WebTarget within each iteration of forEach() (dont want to loose out on the lambda expression conciseness!!!)

any help is appreciated!!!


Solution

  • Try to use:

    public WebTarget webTarget(String path, Map<String, String> queryMap) {
        final WebTarget[] webTarget = {this.client.target(this.address.getUrl()).path(path)};
        if (queryMap != null)
            queryMap.forEach((key, value) -> webTarget[0] = webTarget[0].queryParam(key, value));
    
        return webTarget[0];
    }
    

    But I nevertheless think that it is better to use a for each.

    public WebTarget webTarget(String path, Map<String, String> queryMap) {
        WebTarget webTarget = client.target(this.address.getUrl()).path(path);
        if (queryMap != null)
            for (Map.Entry<String, String> entry: queryMap.entrySet())
                webTarget = webTarget.queryParam(entry.getKey(), entry.getValue());
        return webTarget;
    }