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

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

DDD
DDDOriginal
2024-12-26 19:25:10446browse

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

Parse a URI String into Name-Value Collection

Overview

When dealing with URIs (Uniform Resource Identifiers), it's often useful to parse the query string into a collection of name-value pairs. In Java, there is no built-in method equivalent to the C#/.NET HttpUtility.ParseQueryString method. However, there are various ways to achieve this using custom code.

Using a Custom Method

One way to parse a URI string into a Map is to create a custom method. Here's a simplified version:

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

Improved Method with URL Decoding and Handling Multiple Parameters

The above method has been updated to handle multiple parameters with the same key and parameters with no value. Here's the improved version:

public static Map<String, List<String>> splitQuery(URL url) throws UnsupportedEncodingException {
    final Map<String, List<String>> queryPairs = new LinkedHashMap<>();
    final String[] pairs = url.getQuery().split("&");
    for (String pair : pairs) {
        final int idx = pair.indexOf("=");
        final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
        if (!queryPairs.containsKey(key)) {
            queryPairs.put(key, new LinkedList<>());
        }
        final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
        queryPairs.get(key).add(value);
    }
    return queryPairs;
}

Java 8 Version

Here's a Java 8 version of the method:

public Map<String, List<String>> splitQuery(URL url) {
    if (Strings.isNullOrEmpty(url.getQuery())) {
        return Collections.emptyMap();
    }
    return Arrays.stream(url.getQuery().split("&"))
            .map(this::splitQueryParameter)
            .collect(Collectors.groupingBy(SimpleImmutableEntry::getKey, LinkedHashMap::new, mapping(Map.Entry::getValue, toList())));
}

public SimpleImmutableEntry<String, String> splitQueryParameter(String it) {
    final int idx = it.indexOf("=");
    final String key = idx > 0 ? it.substring(0, idx) : it;
    final String value = idx > 0 && it.length() > idx + 1 ? it.substring(idx + 1) : null;
    return new SimpleImmutableEntry<>(URLDecoder.decode(key, StandardCharsets.UTF_8), URLDecoder.decode(value, StandardCharsets.UTF_8));
}

Usage Example

To use the splitQuery method, simply pass in a URL object and it will return a Map containing the parsed query string parameters:

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> queryParameters = splitQuery(url);

Accessing the values from the Map is straightforward:

String clientId = queryParameters.get("client_id"); // SS

The above is the detailed content of How to Parse a URI Query 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