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.

JavaData Fetching

Code

snippet
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

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:`.