'Replace space for %20 in Spring with UriCompnentsBuilder

I've got a method that takes some parameters and forms a URI from them in order to access our client REST service. It may occur of one of these parameters be a space. The problem is that UriComponentsBuilder.pathSegment ignores space. So, let say, 'v1', ' ', 'v2'... would form the URI .../v1/v2 instead of /v1/%20/v2. If I pass %20 directly to pathSegment, it will replace by %2520. This is my function

 private String getJsonStringFromDetranRestParams(String url, String... params) {

    URI targetUrl = UriComponentsBuilder.fromUriString(url).pathSegment(params).build().encode().toUri();
    String json = restTemplate.getForObject(targetUrl, String.class);

    return json;
}

Is there any kind of 'escape character' to the function so it will see %20 as a valid string instead of a special string. I'm looking for a \\ Java equivalent.



Solution 1:[1]

Just use build() to return it as String, space will be ignored in pathSegment you have to pass %20

String targetUrl = UriComponentsBuilder.fromUriString("http://localhost:8080").pathSegment("v1","%20","v2").build().toUriString();
System.out.println(targetUrl);  //http://localhost:8080/v1/%20/v2

or use build(true) to encode

 URI targetUrl = UriComponentsBuilder.fromUriString("http://localhost:8080").pathSegment("v1","%20","v2").build(true).toUri();
System.out.println(targetUrl); ////http://localhost:8080/v1/%20/v2

Solution 2:[2]

Correct way to do this with UriComponentsBuilder is as follows:

UriComponentsBuilder.fromUriString("http://localhost:8080").encode().build().toUri()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Tomislav Brabec