How do I use java.net.URI with Builder API?

Actually, the standard java.net.URI class in the JDK does not have a built-in Builder API. It only provides constructors and the URI.create(String) factory method.

To build URIs using a builder pattern in Java, you have three common options:

1. Using URI Constructors (Standard JDK)

While not a “builder,” the multi-argument constructor is the safest way to build a URI from components because it automatically handles URL encoding (escaping spaces, special characters, etc.).

import java.net.URI;

URI uri = new URI(
    "https",           // Scheme
    "example.com",     // Host
    "/api/search",     // Path
    "q=java builder",  // Query
    null               // Fragment
);

2. Using UriComponentsBuilder (Spring Framework)

If you are working in a Spring environment, this is the most robust and popular builder API.

import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;

URI uri = UriComponentsBuilder.newInstance()
    .scheme("https")
    .host("example.com")
    .path("/api/users/{id}")
    .queryParam("format", "json")
    .buildAndExpand(123) // Replaces {id} with 123
    .toUri();

3. Using HttpUrl (OkHttp Library)

If you use the OkHttp library, it provides a very clean HttpUrl builder.

import okhttp3.HttpUrl;
import java.net.URI;

URI uri = new HttpUrl.Builder()
    .scheme("https")
    .host("example.com")
    .addPathSegment("search")
    .addQueryParameter("q", "java")
    .build()
    .uri(); // Converts to java.net.URI

4. Why not HttpRequest.newBuilder()?

In your context attachments, you see HttpRequest.newBuilder(). Note that this builds an HTTP Request, not the URI itself. You still need to pass a URI object to the .uri() method:

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://example.com")) // Still requires a URI object
    .GET()
    .build();

Summary: If you want a builder API for java.net.URI without adding external dependencies, your best bet is to create a small helper class or use the multi-argument new URI(...) constructor to ensure proper encoding.