Developer Documentation
Java
Updated September 19, 2026

URL Encoding and Decoding in Java

Percent-encode URL components correctly and distinguish path, query, and form encoding in Java.

URL encoding is context-sensitive. A path segment, a query value, and application/x-www-form-urlencoded data do not use exactly the same escaping rules, so prefer APIs designed for the specific component you are building.

Quick Start#

The following example uses the standard Java API or a widely used package for this task.

Query/form value#

Java
1import java.net.URLEncoder;2import java.net.URLDecoder;3import java.nio.charset.StandardCharsets;45String encoded = URLEncoder.encode("café & tea", StandardCharsets.UTF_8);6String decoded = URLDecoder.decode(encoded, StandardCharsets.UTF_8);7System.out.println(encoded);

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Path segment with URI#

Java
1URI uri = new URI(2    "https",3    "example.com",4    "/files/report 2026.pdf",5    null6);7System.out.println(uri.toASCIIString());

Important Notes#

URLEncoder is for HTML form/query-style data, not arbitrary path segments. Use URI-building APIs for structured URLs.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement URL Encoding in other languages: