Scrivio Interview library
DebuggingFoundations8 min read · updated 12 November 2026

A service builds a redirect URL with "https://shop.example/search?q=" + URLEncoder.encode(term, UTF_8) and a file path with "/files/" + URLEncoder.encode(name, UTF_8). Search for "a b" works, but a file named "my report.pdf" returns 404. Explain, and describe when to use URL encoding, HTML escaping and Base64.

URLEncoder produces application/x-www-form-urlencoded data, the format of HTML form submissions, in which a space becomes +. That is correct inside a query string, which servers decode as form data, but in a path segment + is just a plus, so the server looks for a file literally named my+report.pdf and returns 404. We build URIs with a builder that encodes each part for where it goes, such as Spring's UriComponentsBuilder with encode(), and we keep the other encodings for their own jobs: HTML escaping protects text inserted into HTML against XSS, and Base64 turns binary data into text and is not encryption.

Why this question is asked

Encoding bugs are among the most confusing bugs we meet, because the same input works in one place and fails in another, and because several encodings look alike: a percent sign here, an ampersand there. Mixing them up causes broken links, failed downloads and, in the worst case, security holes. Interviewers ask this question to see whether we understand that each encoding belongs to a specific context. In this answer, we will recap the encodings involved, see exactly why the search works and the file fails, build both URLs correctly, and then look at HTML escaping and Base64, ending with the rule that ties them together.

1A Quick Recap: Encodings Belong to Places

An encoding rewrites characters that have a special meaning in some context so that they are read as plain data. A URL has several contexts with different rules, defined in RFC 3986. In the path, the slash separates segments and a space must be written as %20, the percent sign followed by the character's byte value in hex. In the query string, ampersand and equals sign separate parameters, and by a convention inherited from HTML forms, a space may also be written as +.

That form convention is a separate format with its own name, application/x-www-form-urlencoded, and it is what java.net.URLEncoder produces, despite its general-sounding name. So URLEncoder is correct for query parameter values and form bodies, and wrong for paths.

2Why the Search Works and the File Returns 404

Let us look at what the two concatenations actually produce.

Java
URLEncoder.encode("a b", UTF_8); // a+b
URLEncoder.encode("my report.pdf", UTF_8); // my+report.pdf
"https://shop.example/search?q=" + URLEncoder.encode("a b", UTF_8);
// https://shop.example/search?q=a+b the server reads q as "a b"
"/files/" + URLEncoder.encode("my report.pdf", UTF_8);
// /files/my+report.pdf the server reads the file name as "my+report.pdf"

When the server receives the search request, it decodes the query string as form data, where + means space, so q is a b and the search works. When it receives the file request, it decodes the path by RFC 3986 rules, where + has no special meaning and stays a plus. The file name becomes my+report.pdf, no such file exists, and we get a 404. The file name would have needed %20, which is what path encoding produces.

3Building URIs With a Builder

Concatenating strings means we must remember which encoding each piece needs. A URI builder does it for us, because it knows whether each value goes into a path segment or a query parameter. In Spring, UriComponentsBuilder with encode() before expanding a template encodes every variable strictly for its position.

Java
UriComponentsBuilder.fromUriString("https://shop.example/files/{name}")
.encode().buildAndExpand("my report.pdf").toUri();
// https://shop.example/files/my%20report.pdf
UriComponentsBuilder.fromUriString("https://shop.example/files/{name}")
.encode().buildAndExpand("a/b+c.pdf").toUri();
// https://shop.example/files/a%2Fb%2Bc.pdf the slash and plus are data, not structure
UriComponentsBuilder.fromUriString("https://shop.example/search").queryParam("q", "{q}")
.encode().buildAndExpand("a b&c=d+e").toUri();
// https://shop.example/search?q=a%20b%26c%3Dd%2Be
new URI("https", "shop.example", "/files/my report.pdf", null).toASCIIString();
// https://shop.example/files/my%20report.pdf the JDK alternative
One value, three contexts
ContextRight toola b/c&d becomes
URL path segmentUriComponentsBuilder template variablea%20b%2Fc%26d
Query value or form bodyURLEncoder or UriComponentsBuildera+b%2Fc%26d (form) or a%20b%2Fc%26d
HTML textTemplate engine or OWASP Encodera b/c&d
Binary to textBase64 encoderNot for text; for bytes such as images
The same characters need different treatment in each place, which is why one encoder cannot serve all of them.

Notice the second example: a file name containing a slash is encoded as %2F, so it cannot be mistaken for a second path segment, and a plus becomes %2B, so it survives intact. The JDK's multi-argument URI constructors also encode illegal characters, but they leave reserved characters such as / and & alone, so a value containing them can still change the URL's structure. For values from users, the Spring builder with template variables, or encoding each query value with URLEncoder and each path segment separately, is safer.

4HTML Escaping Is a Different Job

When we insert text into an HTML page, the dangerous characters are different: <, >, &, quotes. If a user's input such as <script>...</script> is inserted as-is, the browser runs it, which is cross-site scripting, or XSS. HTML escaping turns those characters into entities such as &lt; so that the browser shows them as text.

Java
// Thymeleaf escapes by default
<p th:text="${comment}">...</p> // <script> is shown as text, not run
// Outside a template engine, the OWASP Java Encoder:
Encode.forHtml("<b>Ana & Bo</b>"); // &lt;b&gt;Ana &amp; Bo&lt;/b&gt;
Encode.forHtmlAttribute(value); // for values inside attribute quotes
URLEncoder.encode("<script>", UTF_8); // %3Cscript%3E not a substitute for HTML escaping

URL encoding and HTML escaping are not interchangeable. A link in an HTML page may need both: first the value is URL-encoded to build the URL, then the whole URL is HTML-escaped where it is written into the href attribute.

5Base64 Turns Bytes Into Text

Base64 solves a third problem: carrying binary data, such as an image or a signature, through a channel that only accepts text, like JSON or an email header. It maps every 3 bytes to 4 characters from a 64-character alphabet. It hides nothing, since anyone can decode it, so it is never a form of encryption or protection for secrets.

Java
byte[] data = {(byte) 0xfb, (byte) 0xff};
Base64.getEncoder().encodeToString(data); // +/8= contains + and /
Base64.getUrlEncoder().withoutPadding().encodeToString(data); // -_8 safe in URLs and file names
Base64.getDecoder().decode("+/8="); // the original two bytes

The standard alphabet uses + and /, which have meanings in URLs, so for tokens in URLs or file names we use the URL-safe encoder, which uses - and _ instead, often without the = padding.

6The Rule: Encode for the Context, at Output, Once

All of these bugs follow from one rule. We keep data in its raw form inside the program, and we encode it at the moment it leaves for a specific context, with the encoder made for that context: path encoding for a path segment, form encoding for a query value, HTML escaping for HTML, Base64 for bytes in text. Encoding early, when the data enters, is wrong because we do not yet know where it will go. Encoding twice is wrong because the second encoder treats the first one's output as data, which leads to double encoding.

7Follow-up questions

What is double encoding and how does it cause bugs?

Double encoding happens when a value that is already encoded is encoded again. A space becomes %20 the first time, and the second time the percent sign itself is encoded, giving %2520. The receiver decodes once and sees the literal text %20 instead of a space, so file names, search terms and redirects are wrong. A common cause is passing an already-encoded string to UriComponentsBuilder with encode(), or encoding a value before storing it and again when building a link. In security it can also be an attack: a filter that decodes once to look for ../ can miss %252e%252e%252f, which a later layer decodes into ../. The fix is to keep values raw and encode exactly once at output.

Is URLEncoder simply broken?

No, it does exactly what its documentation says: it converts a string to the application/x-www-form-urlencoded format. Its name is the problem, because it suggests a general URL encoder. It is the right tool for each name and value in a query string or a form body, encoded separately, and the wrong tool for paths, fragments or whole URLs. Since Java 10 it also takes a Charset, and we should always pass UTF-8.

Does Spring decode path variables for us?

Yes. When a request for /files/my%20report.pdf reaches a controller method with @PathVariable String name, Spring decodes it and name is my report.pdf. That is why a client must encode the path correctly: the server will decode %20 to a space, but it will leave a + as a plus. Encoded slashes, %2F, are rejected by default by Spring Security's firewall and many servers, so file names with slashes are better passed as query parameters or ids.

8Conclusion

In this answer, we saw that URLEncoder produces form encoding, where a space becomes +, which servers decode as a space only in query strings and forms, so the path /files/my+report.pdf asks for a file with a plus in its name. We built URIs with UriComponentsBuilder and encode(), which encodes each value for its position, and kept HTML escaping for inserting text into HTML against XSS and Base64, with its URL-safe variant, for carrying bytes as text. The rule is to encode for the context, at the point of output, exactly once.

What to say in the interviewAbout 90 seconds aloud

Open with

URLEncoder isn't a general URL encoder; it produces application/x-www-form-urlencoded, the HTML form format, where a space becomes a plus. In the query string that's fine, because servers decode query parameters as form data, so q equals a plus b is read as a b and the search works.

Then, if they want more

In a path segment the rules are RFC 3986, where plus is just a literal plus, so /files/my+report.pdf asks for a file called my+report.pdf and returns 404; the path needed %20.

The fix is to stop concatenating and use a builder that knows where each value goes, like Spring's UriComponentsBuilder with a template variable and encode, which gives %20 in the path and also encodes slashes and pluses inside the value. The JDK's multi-argument URI constructor works for simple cases but leaves reserved characters alone.

Then the other encodings: HTML escaping is for inserting text into HTML, turning angle brackets, ampersands and quotes into entities to prevent XSS; template engines like Thymeleaf do it by default, or I use the OWASP Java Encoder for the specific context.

Base64 is for carrying binary data as text, like images in JSON; it's not encryption, and for URLs I use the URL-safe encoder, which replaces plus and slash. The general rule is to keep data raw, encode for the context at the point of output, and encode exactly once, because encoding twice turns %20 into %2520.

About this answer

Last updated
12 November 2026
Versions it names
Java 10
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A service builds a redirect URL with "https://shop.example/search?q=" +...": https://scrivio-interview-library.netlify.app/java/strings/6b4b850bb7/