URLEncoder Encodes Form Query Values
URLEncoder encodes query values with StandardCharsets.UTF_8 so spaces become plus signs and structural characters stay escaped in the query string.
Code
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class QueryBuilder {
public static void main(String[] args) {
// & and = are query-string structure chars; values must escape them
String encoded = URLEncoder.encode("blue shoes & more", StandardCharsets.UTF_8);
System.out.println("value: " + encoded);
// spaces encode as +: a form/query convention; URL paths use %20 instead
System.out.println("plus: " + URLEncoder.encode("a b", StandardCharsets.UTF_8));
// a literal plus is encoded too, removing the space ambiguity
System.out.println("plus char: " + URLEncoder.encode("c++", StandardCharsets.UTF_8));
// decoding reverses it: + becomes a space again
System.out.println("decoded: " + URLDecoder.decode(encoded, StandardCharsets.UTF_8));
}
}What the demo escapes
The value blue shoes & more encodes under UTF-8 into blue+shoes+%26+more: the space becomes a plus, and the ampersand, a query-string structure character, turns into %26 so it cannot split parameters.
The special cases get their own lines: a plain space prints a+b, while the literal plus in c++ encodes to c%2B%2B so it cannot be mistaken for an encoded space. URLDecoder.decode reverses the whole thing, printing the original text back.
Caveats and details
-
- only means space inside form/query contexts.
- Always pass an explicit charset; the single-arg overload is deprecated.
Interactive Tools for This Topic
Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.URL Encoder & DecoderEncode and decode URLs and their components safely. Switch between encodeURIComponent and encodeURI modes to handle query parameters, paths, and special characters.URL Query String SerializerParse a URL query string into decoded key/value pairs or serialize key=value lines into a percent-encoded query string with duplicate-key detection.
FAQ
- Why does a literal plus need escaping?
- Because decoders turn + into a space; encoding c++ as c%2B%2B keeps the plus characters intact, as the printed plus char line demonstrates.
Report a problem with this exampleOpens a pre-filled issue on GitHub.