Enterprise Java

Quickly creating URIs with UriBuilder

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:

1
2
3
4
5
6
7
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.

Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: Quickly creating URIs with UriBuilder

Opinions expressed by Java Code Geeks contributors are their own.

Sebastian Daschner

Sebastian Daschner is a self-employed Java consultant and trainer. He is the author of the book 'Architecting Modern Java EE Applications'. Sebastian is a Java Champion, Oracle Developer Champion and JavaOne Rockstar.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button