Table of Contents
Parse a URI String into Name-Value Collection
Overview
Using a Custom Method
Improved Method with URL Decoding and Handling Multiple Parameters
Java 8 Version
Usage Example
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?

Dec 26, 2024 pm 07:25 PM

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;
}
Copy after login

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;
}
Copy after login

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));
}
Copy after login

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);
Copy after login

Accessing the values from the Map is straightforward:

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

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)