Home >Java >javaTutorial >How to Parse URI Query Strings into Name-Value Pairs in Java Without External Libraries?
Parsing URI strings into their constituent elements is a common task in web development. To accomplish this task, Java provides several built-in capabilities and external libraries. This article focuses on a Java-based solution for parsing URI strings without using external dependencies.
The query portion of a URI contains a series of name-value pairs separated by the '&' character. To parse these parameters into a map, you can use the following method:
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; }
Using the given URL as an example:
https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/Callback
The splitQuery method will return the following map:
{client_id=SS, response_type=code, scope=N_FULL, access_type=offline, redirect_uri=http://localhost/Callback}
The method includes URL decoding to handle any special characters present in the parameter values.
An updated version of the method has been provided to handle scenarios where multiple parameters have the same key. This version uses a Map
A Java 8 implementation of the method is also available, which leverages lambda expressions and streams for a concise and efficient solution.
By using the splitQuery method, you can easily parse URI query strings into their constituent name-value pairs without relying on external libraries. This capability is essential for various web development tasks, such as extracting user input or retrieving parameters from RESTful endpoints.
The above is the detailed content of How to Parse URI Query Strings into Name-Value Pairs in Java Without External Libraries?. For more information, please follow other related articles on the PHP Chinese website!