How to decode URL-encoded and URL query strings in Java

2 Answers

0 votes
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

public class UrlDecoderExample {

    /**
     * Decodes a URL-encoded string or query component.
     * Automatically handles percent-encoding (%xx) and '+' to space conversion.
     *
     * @param encodedStr The URL-encoded string.
     * @return The fully decoded string, or the original string if an error occurs.
     */
    public static String decodeUrlString(String encodedStr) {
        try {
            // URLDecoder handles both %xx escapes and '+' to space conversion
            return URLDecoder.decode(encodedStr, StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            System.err.println("Decoding error: " + e.getMessage());
            return encodedStr;
        }
    }

    public static void main(String[] args) {
        // Example 1: Standard URL encoding with special characters
        String sample1 = "Hello%20World%21%20Java%20%26%20Web";
        System.out.println("--- Example 1: Standard URL Encoding ---");
        System.out.println("Encoded: " + sample1);
        System.out.println("Decoded: " + decodeUrlString(sample1));

        // Example 2: Form query string fragment encoding (spaces represented as '+')
        String sample2 = "Jane+Doe+from+New+York";
        System.out.println("\n--- Example 2: Form Fragment Encoding ---");
        System.out.println("Encoded: " + sample2);
        System.out.println("Decoded: " + decodeUrlString(sample2));
    }
}


/*
run:

--- Example 1: Standard URL Encoding ---
Encoded: Hello%20World%21%20Java%20%26%20Web
Decoded: Hello World! Java & Web

--- Example 2: Form Fragment Encoding ---
Encoded: Jane+Doe+from+New+York
Decoded: Jane Doe from New York

*/

 



answered 42 minutes ago by avibootz
0 votes
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;

public class QueryStringParserExample {

    /**
     * Parses and decodes a complete URL query string into a Map.
     *
     * @param queryString The URL query string (with or without leading '?').
     * @return A Map where each key maps to a list of decoded values.
     */
    public static Map<String, List<String>> parseAndDecodeQuery(String queryString) {
        // Remove leading '?' if present
        if (queryString != null && queryString.startsWith("?")) {
            queryString = queryString.substring(1);
        }

        Map<String, List<String>> result = new HashMap<>();
        if (queryString == null || queryString.isEmpty()) {
            return result;
        }

        // Split query into individual key-value pairs
        String[] pairs = queryString.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            try {
                String key, value;
                if (idx > 0) {
                    key = URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8.name());
                    value = URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name());
                } else {
                    key = URLDecoder.decode(pair, StandardCharsets.UTF_8.name());
                    value = "";
                }

                // Group values by key to handle multi-value parameters
                result.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
            } catch (Exception e) {
                System.err.println("Error decoding pair: " + pair);
            }
        }

        return result;
    }

    public static void main(String[] args) {
        String fullQuery = "search=java+tutorial&category=programming&tag=beginner&tag=backend";

        System.out.println("--- Full Query String Parsing ---");
        System.out.println("Original Query: " + fullQuery);

        Map<String, List<String>> decodedMap = parseAndDecodeQuery(fullQuery);

        System.out.println("Decoded Map Result:");
        for (Map.Entry<String, List<String>> entry : decodedMap.entrySet()) {
            System.out.println("  " + entry.getKey() + " -> " + entry.getValue());
        }
    }
}


/*
run:

--- Full Query String Parsing ---
Original Query: search=java+tutorial&category=programming&tag=beginner&tag=backend
Decoded Map Result:
  search -> [java tutorial]
  tag -> [beginner, backend]
  category -> [programming]

*/

 



answered 39 minutes ago by avibootz
...