URL Encoder Query Param Roundtrip
Encode every key and value with URLEncoder before joining the query string: form rules turn spaces into + and escape &, and URLDecoder reverses it.
Code
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
public class QueryBuilder {
public static void main(String[] args) {
Map<String, String> params = new LinkedHashMap<>();
params.put("q", "java NIO & files");
params.put("lang", "zh-CN");
params.put("tag", "café");
StringBuilder query = new StringBuilder();
for (Map.Entry<String, String> p : params.entrySet()) {
if (query.length() > 0) {
query.append('&');
}
// Encode each key and value separately: &, =, spaces must never go raw into a URL
query.append(URLEncoder.encode(p.getKey(), StandardCharsets.UTF_8))
.append('=')
.append(URLEncoder.encode(p.getValue(), StandardCharsets.UTF_8));
}
System.out.println("query: " + query);
// URLEncoder follows form rules: spaces become +, not %20
String encoded = URLEncoder.encode("a b", StandardCharsets.UTF_8);
System.out.println("space: " + encoded);
// Decoding restores the original values, + back to space
System.out.println("decoded: " + URLDecoder.decode(encoded, StandardCharsets.UTF_8));
}
}What the code does
URL Encoder Query Param Roundtrip keeps everything in the class QueryBuilder and the function main.
The file repeats itself only inside for (Map.Entry<String, String> p : params.entrySet()).
Applying it
The demo output is labeled (query:, space:, decoded:), so every printed line maps back to its originating operation.
Statements that matter
query.append(URLEncoder.encode(p.getKey(), StandardCharsets.UTF_8))
.append('=')
.append(URLEncoder.encode(p.getValue(), StandardCharsets.UTF_8));
String encoded = URLEncoder.encode("a b", StandardCharsets.UTF_8);
Map<String, String> params = new LinkedHashMap<>();
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
- What does URL Encoder Query Param Roundtrip print when run?
- Execute the whole file; each printed line is prefixed with a label like `query:`, `space:`, `decoded:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.