sebastiandaschner blog


Quickly creating URIs with UriBuilder

#jaxrs wednesday, april 01, 2020

If you have access to the JAX-RS API and an implementation in your projects (many do), then you can use JAX-RS' UriBuilder to conveniently create URIs via builder pattern using resolvable placeholder.

Have a look at the following example:

String host = System.getProperty("host", "localhost");
String port = System.getProperty("port", "8080");

URI uri = UriBuilder.fromUri("http://{host}:{port}/examples")
        .path("123")
        .queryParam("sort", "name")
        .build(host, port);

Depending on whether the system properties are present, the resulting uri will be http://localhost:8080/examples/123?sort=name, or any host and port which is overridden.

This is a convenient way to create flexible URIs for tests where the target system may change for different scopes. This API is available in everything that supports JAX-RS, for example Open Liberty, Quarkus, or other Jakarta or MicroProfile implementations.

This post has been reposted from my newsletter issue 040.

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: