2

I'm writing a REST API endpoint with pagination and I want it to include the links to the first, previous, next and last pages. I also want these links to include whatever parameters that were sent in the original request (BTW is that a bad idea?).

I'm using the UriBuilder class to create those links. My function looks like this:

private static URI createUri(String endpoint, 
    MultivaluedMap<String, String> queryParameters) {
    final UriBuilder uriBuilder = UriBuilder.fromPath(endpoint);
    queryParameters.forEach(
        (key, valueList) -> valueList.forEach(
            value -> uriBuilder.queryParam(key, value)));
    return uriBuilder.build();
}

Now, I don't want the parameters in this links to be encoded, since they should be readable by whoever is going to use the API. the problem is that UriBuilder.queryParam() seams to always encode them.

I could simply concatenate the parameters to the endpoint but I feel that this would be to reinvent the wheel. So I'm wondering if there's a better way to do it.

uzilan
  • 2,554
  • 2
  • 31
  • 46
  • When you create a URI, the parameters always have to be URI-encoded. Otherwise you don't get a valid URI - for example, if one of your parameters includes a '/'. – RealSkeptic Aug 08 '18 at 10:02
  • Ok, so in other words, concatenate? – uzilan Aug 08 '18 at 10:43
  • 2
    So, in other words, if you want to have valid links, have them encoded. Links without encoding are not valid links. They can't be fetched properly from a valid server. Do not concatenate - you'll not end up with a URI. – RealSkeptic Aug 08 '18 at 10:48

1 Answers1

0
uriBuilder.build(false).toUriString()
Syscall
  • 19,327
  • 10
  • 37
  • 52
Alex
  • 454
  • 5
  • 5
  • 2
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/9193372) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made. – Syscall Mar 16 '21 at 11:58