Question

Java URL Encode Query Parameters Correctly

javahttpurlencodingurlencode

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

%A3 alone is not a valid UTF-8 encoding of £.

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.

Take Quiz

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:

String encodedQuery = URLEncoder.encode(query, "UTF-8")
        .replace("+", "%20");

This overload declares UnsupportedEncodingException, so place it in a method that handles or declares that exception. UTF-8 is required by Java implementations, so the exception is not a practical concern when the literal is exactly "UTF-8".

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:

  1. query contains the user text cats & dogs.

  2. 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.
  3. .replace("+", "%20") changes the encoded spaces:

    cats%20%26%20dogs
    
  4. Concatenating the base URL and encoded value produces:

    https://example.com/search?q=cats%20%26%20dogs
    

The server can decode the q parameter back to the original text without accidentally creating another parameter.

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 Paulo or ?status=in progress.
  • Pagination and sorting: values such as ?sort=price desc must not leave raw spaces in a URL.
  • Maps and geocoding: an address like 10 Downing St, London is 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.
Take Quiz

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:

String once = "cats%20dogs";
String twice = URLEncoder.encode(once, StandardCharsets.UTF_8);
// "cats%2520dogs"

% becomes %25, changing the meaning. Keep values raw until the one point where you serialize them into a URL.

Leaving delimiter characters unencoded

This is unsafe when userInput can contain & or =:

String url = "https://example.com/search?q=" + userInput;

For input tea&admin=true, the server may interpret admin=true as a separate parameter. Encode userInput first.

Assuming %A3 represents £ in UTF-8

£ is %C2%A3 in UTF-8. A percent-encoded URL is a sequence of encoded bytes, not simply a character's numeric code.

Comparisons

SituationRecommended approachWhy
Encode a single query valueURLEncoder.encode(value, UTF_8)Designed for form/query-style values.
Need %20 rather than + for spacesEncode, then replace + with %20URLEncoder follows form encoding, where + means space.
Build a URL with several dynamic parametersUse a project-approved URI/HTTP client builderReduces manual separator and encoding mistakes.
Parse a URLUse URI or a URL/HTTP library parserParsing is different from encoding user input.
Encode a URL path segmentUse a path-aware URI builderPath rules differ from query form rules.

URLEncoder is named broadly, but it is not a general “encode any whole URL” method. Its behavior is specifically aligned with HTML form encoding. That is why its space output is +.

Take Quiz

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.
  • URLEncoder converts spaces to +.
  • %20 is another valid URL representation of a space.
  • £ in UTF-8 is %C2%A3.
  • Encode once only; double encoding changes % into %25.
  • Encode parameter names too if their names are dynamic.
  • Use & and = only as URL structure, not inside raw values.

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.

Should I use URL, URI, or URLEncoder?

Use URLEncoder for individual query values. Use URI or a URL/HTTP library to represent, parse, or build the full URL. They solve different parts of the problem.

Is string concatenation always wrong for query strings?

It is acceptable for a fixed base URL and a small number of values that you encode correctly. For many optional parameters, use a builder or helper to reduce mistakes.

What Java version supports URLEncoder.encode(value, StandardCharsets.UTF_8)?

The overload accepting a Charset is available in Java 10 and later. In Java 8 or 9, use URLEncoder.encode(value, "UTF-8") and handle its declared exception.

Take Quiz

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

  1. Create a method that encodes one query parameter value using UTF-8.
  2. Convert form-style + space markers to %20.
  3. Build a URL with q and category query parameters.
  4. Test the method with a search phrase containing spaces, £, and $.
  5. Ensure an ampersand inside the search phrase is encoded rather than treated as a separator.
Take Quiz

Keep learning

Related questions

View more