Question
Given the base URL:
http://example.com/query?q=
and a user-entered query such as:
random word £500 bank $
how can I create a properly encoded URL in Java? The query value should be encoded safely as a query-string parameter, including spaces, the pound sign, and the dollar sign. I tried URLEncoder and constructing URI/URL objects, but the output did not match the expected format.
Short Answer
You will learn that a URL query value must be encoded separately from the URL structure. In Java, URLEncoder is appropriate for encoding form-style query parameters, but it represents spaces as +. If an API requires spaces as %20, replace those + characters after encoding. You will also learn why £ must be UTF-8 encoded as %C2%A3, not %A3.
Concept
A URL has structural characters with special meanings:
http://example.com/query?q=value&sort=date
^ ^
| |
parameter separator
Do not encode the entire URL as one string. Instead, keep the structure (http, host, path, ?, =, and &) intact and encode each user-provided parameter value.
For example, in this URL:
http://example.com/query?q=random word £500 bank $
only this value comes from the user and needs encoding:
random word £500 bank $
Java's URLEncoder performs application/x-www-form-urlencoded encoding, the format commonly used for HTML forms and query strings. It converts text to bytes using a character set such as UTF-8, then escapes bytes that cannot safely appear in a parameter value.
UTF-8 matters for non-ASCII characters. The character £ is represented by two UTF-8 bytes, C2 and A3, so its correct percent-encoded form is:
%C2%A3
Mental Model
Think of a URL as a shipping label:
- The URL structure is the printed layout: destination, sections, and separators.
- User input is the package contents.
- Encoding is wrapping the contents so they cannot be mistaken for part of the label.
A space, &, or = inside user input could otherwise change how a server reads the URL. For example, an unencoded & may look like the start of a new parameter. Encode the user input before attaching it to the URL, but do not wrap or alter the label itself.
Syntax and Examples
Use URLEncoder.encode on an individual query parameter value.
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
String query = "random word £500 bank $";
String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8)
.replace("+", "%20");
String url = "http://example.com/query?q=" + encodedQuery;
System.out.println(url);
Output:
http://example.com/query?q=random%20word%20%C2%A3500%20bank%20%24
URLEncoder initially produces this form:
random+word+%C2%A3500+bank+%24
In form encoding, + represents a space. Many servers accept it in a query string. Replace + with %20 only when you specifically need percent-encoded spaces, such as when matching an API example or a strict expected URL format.
For Java 8 and Java 9, use the overload that accepts the charset name:
Step by Step Execution
Consider this code:
String query = "cats & dogs";
String encoded = URLEncoder.encode(query, StandardCharsets.UTF_8)
.replace("+", "%20");
String url = "https://example.com/search?q=" + encoded;
Step by step:
-
querycontains the user textcats & dogs. -
URLEncoder.encode(...)applies UTF-8 form encoding:cats+%26+dogs- Each space becomes
+. &becomes%26, so it cannot be interpreted as a separator between query parameters.
- Each space becomes
-
.replace("+", "%20")changes the encoded spaces:cats%20%26%20dogs
Real World Use Cases
Encoding individual query values is useful whenever text becomes part of a URL:
- Search pages:
?q=receives a search term containing spaces, symbols, or non-English text. - REST API requests: a client sends filters such as
?city=São Pauloor?status=in progress. - Pagination and sorting: values such as
?sort=price descmust not leave raw spaces in a URL. - Maps and geocoding: an address like
10 Downing St, Londonis sent as a query parameter. - Redirect links: an application includes a destination path in
?next=. Encoding prevents its?and&characters from breaking the outer URL. - Command-line tools and scripts: a script constructs URLs from user input, CSV data, or environment variables.
Real Codebase Usage
In real projects, avoid scattering URL string concatenation throughout the code. Put encoding near the point where parameters are added.
A small helper makes the intent explicit:
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
static String encodeQueryValue(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8)
.replace("+", "%20");
}
Use it for every dynamic value:
String url = "https://api.example.com/search"
+ "?q=" + encodeQueryValue(searchTerm)
+ "&page=" + encodeQueryValue(String.valueOf(page));
For more than a few parameters, prefer an HTTP client or URI-building library supplied by your project. Such tools can accept parameter names and values separately, then serialize them safely. The key rule remains the same: pass raw values to the builder and let one component encode them exactly once.
Also validate input before encoding when business rules require it. Encoding makes text safe for transport; it does not prove that a search term, page number, redirect destination, or filter is allowed.
Common Mistakes
Encoding the complete URL
This is incorrect because it encodes structural characters such as : and /:
String broken = URLEncoder.encode(
"https://example.com/search?q=cats",
StandardCharsets.UTF_8
);
The result begins with https%3A%2F%2F..., which is a parameter value, not a usable URL. Encode only dynamic parameter names or values.
Expecting %20 directly from URLEncoder
URLEncoder.encode("two words", StandardCharsets.UTF_8);
// "two+words"
This is normal form encoding. Use .replace("+", "%20") when the required URL representation specifically uses %20.
Using the platform default character set
Avoid charset-less encoding approaches or APIs that rely on defaults. Always specify UTF-8:
URLEncoder.encode(value, StandardCharsets.UTF_8);
Double encoding
Do not encode a value that is already encoded:
Comparisons
| Situation | Recommended approach | Why |
|---|---|---|
| Encode a single query value | URLEncoder.encode(value, UTF_8) | Designed for form/query-style values. |
Need %20 rather than + for spaces | Encode, then replace + with %20 | URLEncoder follows form encoding, where + means space. |
| Build a URL with several dynamic parameters | Use a project-approved URI/HTTP client builder | Reduces manual separator and encoding mistakes. |
| Parse a URL | Use URI or a URL/HTTP library parser | Parsing is different from encoding user input. |
| Encode a URL path segment | Use a path-aware URI builder |
Cheat Sheet
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
String encoded = URLEncoder.encode(rawValue, StandardCharsets.UTF_8);
Use %20 spaces when required:
String encoded = URLEncoder.encode(rawValue, StandardCharsets.UTF_8)
.replace("+", "%20");
Build a URL from a fixed base and encoded values:
String url = baseUrl + "?q=" + encoded;
Rules:
- Encode each user-controlled parameter value, not the entire URL.
- Specify
StandardCharsets.UTF_8. URLEncoderconverts spaces to+.%20is another valid URL representation of a space.£in UTF-8 is%C2%A3.- Encode once only; double encoding changes
%into .
FAQ
Should Java URLEncoder encode spaces as + or %20?
URLEncoder encodes spaces as + because it uses HTML form encoding. Both + and %20 are commonly understood as spaces in query strings, but use %20 when a target API or expected output requires it.
Why is the pound sign encoded as %C2%A3 rather than %A3?
URL percent encoding represents bytes. In UTF-8, £ uses two bytes: C2 and A3. Therefore it must be written as %C2%A3.
Can I encode the entire Java URL with URLEncoder?
No. Encoding the whole URL also escapes its protocol, slashes, and separators. Encode only the dynamic query parameter names and values.
Does URLEncoder protect against malicious input?
It prevents input from breaking query-string syntax, but it does not validate the input's meaning. Still validate values according to your application's rules.
Mini Project
Description
Build a small Java utility that creates a safe product-search URL from a user-entered search term and an optional category. The utility demonstrates encoding each query parameter independently, so spaces, currency symbols, ampersands, and non-English characters cannot alter the query-string structure.
Goal
Create a UTF-8 encoded search URL whose parameter values use %20 for spaces.
Requirements
- Create a method that encodes one query parameter value using UTF-8.
- Convert form-style
+space markers to%20. - Build a URL with
qandcategoryquery parameters. - Test the method with a search phrase containing spaces,
£, and$. - Ensure an ampersand inside the search phrase is encoded rather than treated as a separator.
Keep learning
Related questions
Add External JAR Files to an IntelliJ IDEA Java Project
Learn how to add external JAR dependencies to an IntelliJ IDEA Java project using module libraries, and when to use Maven or Gradle instead.
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Call a Method After a Delay in Android Java
Learn how to run Java code after a delay in Android using Handler.postDelayed, manage the main thread, and cancel callbacks safely.