Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java HTTP query values: encode data without changing URI structure

Last updated: 4 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

A URI query contains syntax as well as data. Encode each value under the receiving endpoint's query convention before joining it to a trusted base URI; do not encode the complete URI as one value.

Operational contract

URLEncoder implements form encoding: a space becomes a plus sign, and other non-safe characters become percent-encoded UTF-8 bytes. That is suitable only when the endpoint decodes its query values as form data. This method requires an HTTPS collection URI with no existing query or fragment, appends exactly one named value, and rejects a null input. A different endpoint may require a different encoding contract, especially for path segments. Keep the base URI in trusted configuration and validate any host supplied by callers before sending a request.

Failure case

A catalog search receives the text 'seal 47 & blue'. The ampersand must remain inside the value; otherwise a server could interpret the tail as another parameter. The method encodes the value, not the separator. It also refuses a base URI that already contains a query because blindly appending a second question mark would change the request target.

Java code

Java
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class CatalogQueryUri {
    public static URI search(URI collection, String searchText) {
        Objects.requireNonNull(searchText, "searchText");
        if (!"https".equalsIgnoreCase(collection.getScheme())
                || collection.getHost() == null
                || collection.getRawQuery() != null
                || collection.getRawFragment() != null) {
            throw new IllegalArgumentException("Expected a bare HTTPS collection URI");
        }
        String value = URLEncoder.encode(searchText, StandardCharsets.UTF_8);
        return URI.create(collection.toASCIIString() + "?q=" + value);
    }
}

Performance and ownership cost

Encoding B UTF-8 bytes takes O(B) time and O(B) output space. The URI conversion creates another string. These costs are small beside a network call, but the endpoint should still set a length limit on accepted searches.

Common Mistakes

  • Do not use URLEncoder on a whole URI or on a path segment.
  • Do not assume every server interprets plus as a space in a query.
  • Do not append a query to a base that already has a query or fragment.

Connected lessons

java
http request and response boundaries
http-query-value-encoding
Storage details