Quick revision
The short answer
Concatenating raw user input into a URL lets the input change the URL's structure: an ampersand starts a new parameter, a hash sign cuts off the rest as a fragment, and a space makes the URL invalid. The fix is to encode each component separately, for example with URLEncoder.encode(value, StandardCharsets.UTF_8) for a query value, or better with a builder such as Spring's UriComponentsBuilder or RestClient URI templates. When users can influence the host or scheme, we must also validate them to prevent server-side request forgery.
What to remember
In this answer, we saw that concatenating input into a URL lets the input supply separators: & and = add parameters, # truncates the query, and spaces make the URL invalid. We fixed it by encoding each query value with URLEncoder.encode(value, StandardCharsets.UTF_8), which uses form encoding with + for spaces, or by letting UriComponentsBuilder or RestClient expand template variables with strict encoding. We never encode a whole URL at once, and when input can choose the host or scheme, we validate it against an allowlist to prevent server-side request forgery.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Concatenating raw user input into a URL lets the input change the URL's structure: an ampersand starts a new parameter, a hash sign cuts off the rest as a fragment, and a space makes the URL invalid. The fix is to encode each component separately, for example with URLEncoder.encode(value, StandardCharsets.UTF_8) for a query value, or better with a builder such as Spring's UriComponentsBuilder or RestClient URI templates. When users can influence the host or scheme, we must also validate them to prevent server-side request forgery.
Why this question is asked
Building a URL with the plus operator is one of the first things we all write, and it works perfectly in every demo, because demo input is a simple word. In production the input is a search term, a name or a product code, and sooner or later it contains a character that means something in URL syntax. Interviewers like this question because it combines a correctness bug, a security bug and a detail of encoding rules that many people get wrong. In this answer, we will recap the structure of a URL, reproduce the failures, encode the value correctly with plain Java, build the URI with Spring, and then look at validating hosts when the input decides where the request goes.
1A Quick Recap of URL Structure
A URL is not a single string to a server; it is a structure with separators. In https://api.example.com/x?q=shoes&page=2#top, the part after ? is the query, & separates one parameter from the next, = separates a parameter's name from its value, and # starts the fragment, which the client keeps for itself and never sends to the server. Characters such as spaces are not allowed at all and must be written in percent-encoding, a percent sign followed by two hex digits for each byte, such as %20 for a space.
Encoding is how we say this character is data, not a separator. %26 is an ampersand that is part of a value, while a raw & ends the value. When we concatenate user input without encoding, we hand the user the power to write separators.
2Reproducing the Failures
Here is the code from the question with three ordinary-looking inputs.
| Character | Meaning in a URL | Encoded as a query value |
|---|---|---|
| & | Starts the next parameter | %26 |
| = | Separates name and value | %3D |
| # | Starts the fragment, not sent to the server | %23 |
| space | Not allowed | + (form encoding) or %20 |
| + | Often decoded as a space in a query | %2B |
| % | Starts a percent-encoded byte | %25 |
| / and ? | Path separator, start of query | %2F and %3F |
Notice that the first input is the security finding. The user did not just search; they added a parameter of their choice. If the downstream service trusts parameters such as limit, role or account, the attacker can change how it behaves. This is called parameter injection. The other two inputs explain the failing requests: a space makes the URI invalid, and a hash sign silently truncates the query.
3Fix 1: Encode Each Query Value With URLEncoder
In plain Java, we encode the value, and only the value, with URLEncoder. Since Java 10 there is an overload that takes a Charset, so we no longer need to pass the string "UTF-8" and catch an exception.
The reason this works is that every character with a special meaning is now percent-encoded, so the server decodes it back into data. Notice the space became +, not %20. URLEncoder implements form encoding, the application/x-www-form-urlencoded format that HTML forms use, where a plus sign means a space. Nearly every server decodes query strings that way, so it is correct for query parameter names and values. It is not correct for a path segment: in a path, + is a literal plus sign, so encoding a file name like my report.pdf with URLEncoder and putting it in the path gives a different file name on the server. For path segments we need a path-aware encoder, which is one reason to prefer a builder.
4Fix 2: Let a Builder Encode the Parts
Spring's UriComponentsBuilder knows which part of the URI each piece belongs to and encodes it with the right rules. The safest pattern is a URI template with variables, because the variables are encoded strictly: everything other than letters, digits and a few unreserved characters is percent-encoded.
Notice the order: encode() is called before the values are expanded. If we instead add the raw value with queryParam("q", userInput) and call build().encode() afterwards, Spring only encodes characters that are illegal in a query, and a + in the value is left as it is, which the server then reads as a space. The template-and-variables style avoids that. RestClient and WebClient use this strict variable encoding by default (check your version for the exact default encoding mode), so passing user input as a URI variable rather than concatenating it into the template string is the habit to build.
5Never Encode the Whole URL at Once
A tempting shortcut is to build the full string and then encode it in one call. That cannot work, because the encoder has no way to know which slashes and question marks are structure and which are data.
It either destroys the separators that should stay, as above, or, with a lenient encoder that leaves separators alone, it leaves the injected & untouched. The rule is simple: encode each component exactly once, at the moment we put it into the URI.
6When Input Decides Where the Request Goes
So far the user only controlled a value. Sometimes they control more: a webhook address, an image to fetch, a partner callback. Then encoding is not enough, because a correctly encoded URL can still point at http://169.254.169.254/, the cloud metadata service, or at an internal admin endpoint. Making our server fetch an address the attacker chose is called server-side request forgery, or SSRF.
The defence is to validate before calling: parse with URI, allow only the schemes we expect (usually https), check the host against an allowlist of domains, and when the host may be anything, resolve it and refuse loopback, link-local and private addresses. We should also disable automatic redirects, or re-check each redirect target, because an allowed host can redirect to a forbidden one.
Because DNS can answer differently at check time and connect time, high-risk features should also go through an egress proxy that enforces the same rules.
7Follow-up questions
Is URLEncoder correct for path segments?
No. URLEncoder does form encoding, where a space becomes + and a slash becomes %2F. In a path, + is a literal plus, so the server sees a different value. For a path segment, use a builder that applies path rules, such as UriComponentsBuilder with a {name} variable in the path, or UriUtils.encodePathSegment in Spring.
Why did the security test manage to add parameters?
Because the input contained an unencoded ampersand and equals sign, which the server's query parser treats as separators. The client built a string, not a structure, so the input could add a new name and value. Encoding the value turns them into %26 and %3D, which the server decodes back into one ordinary value.
8Conclusion
In this answer, we saw that concatenating input into a URL lets the input supply separators: & and = add parameters, # truncates the query, and spaces make the URL invalid. We fixed it by encoding each query value with URLEncoder.encode(value, StandardCharsets.UTF_8), which uses form encoding with + for spaces, or by letting UriComponentsBuilder or RestClient expand template variables with strict encoding. We never encode a whole URL at once, and when input can choose the host or scheme, we validate it against an allowlist to prevent server-side request forgery.
Open with
The problem is that the code builds a URL as a string, so the user's input can contain characters that are part of URL syntax. An ampersand and equals sign add a new parameter, which is exactly what the security test did, a hash sign turns the rest into a fragment that is never sent, and a space makes the URI invalid, which explains the failing requests.
Then, if they want more
The fix is to encode each component separately and only once. In plain Java I would encode the value with URLEncoder.encode and StandardCharsets.UTF_8; that is form encoding, so a space becomes a plus, which is right for query parameters but wrong for path segments.
In Spring I prefer a URI template, either UriComponentsBuilder with a variable, calling encode before expanding, or RestClient's uri method with the input passed as a variable, because variables are strictly encoded, including the plus sign. I would never encode the whole URL at once, because the encoder cannot tell structure from data.
And if the user can influence the host or scheme, for example a callback URL, I would treat it as a server-side request forgery risk: allow only https, check the host against an allowlist, refuse private and metadata addresses, and re-check redirects.
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.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
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 client builds request URLs by string concatenation: "https://api/x?q=" + userInput....": https://scrivio-interview-library.netlify.app/java/networking/f571e35ae6/