Home >Java >javaTutorial >How to Parse a URI String into a Name-Value Collection in Java?

How to Parse a URI String into a Name-Value Collection in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-18 22:05:11579browse

How to Parse a URI String into a Name-Value Collection in Java?

Parse a URI String into Name-Value Collection

Due to the absence of an explicitly defined Java equivalent to C#/.NET's HttpUtility.ParseQueryString method, alternative approaches are necessary to parse URI strings into name-value collections. This answer explores a custom Java implementation that achieves this functionality.

Java Code for URI Parsing

The following Java code can be utilized to split a URI string into a name-value pair collection:

public static Map<String, String> splitQuery(URL url) throws UnsupportedEncodingException {
    Map<String, String> query_pairs = new LinkedHashMap<>();
    String query = url.getQuery();
    String[] pairs = query.split("&");
    for (String pair : pairs) {
        int idx = pair.indexOf("=");
        query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
    }
    return query_pairs;
}

Usage and Example

This method can be invoked with a URL as an argument, and it returns a Map containing the parsed name-value pairs. For instance, using the URI provided in the question:

URL url = new URL("https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/Callback");
Map<String, String> query_pairs = splitQuery(url);
System.out.println(query_pairs.get("client_id")); // prints "SS"

This method facilitates easy access to the parsed values by utilizing the Map interface. It's important to note that URL-decoding is implemented in this method to ensure correct handling of encoded characters in the URI.

Enhancements

Subsequent updates to this solution have addressed additional requirements, such as handling multiple parameters with the same key and parameters without values. Furthermore, a Java8 version has been provided for those using more recent Java versions.

As this response has garnered significant popularity, the provided Java code has been continually refined to offer a more robust and versatile approach to URI parsing.

The above is the detailed content of How to Parse a URI String into a Name-Value Collection in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn