Parse a URI String or URL Query into Name-Value pair in Java

(1428 Views)


You have a URL like this
https://www.solutionfactory.in/data/authorize?id=kk&response_type=code&requestScope=FULL&Status=offline&redirect=http://www.solutionfactory.in
And You want to parse your URL data into collection in Java like this -
Name Value
id kk
response_type code
requestScope FULL
Status offline
redirect http://www.solutionfactory.in


Here is the code to parse URI String into Map in java -

Solution 1

public static Map<String, String> splitQuery(URL url) throws UnsupportedEncodingException { Map<String, String> query_pairs = new LinkedHashMap<String, String>(); 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; }

To access the Map use .get("id"), for the above URL this would return "kk"

Solution 2 - Second Way which handles multiple parameters with the same key and parameters with no value as well.

public static Map<String, List<String>> splitQuery(URL url) throws UnsupportedEncodingException { final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>(); 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 (!query_pairs.containsKey(key)) { query_pairs.put(key, new LinkedList<String>()); } final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; query_pairs.get(key).add(value); } return query_pairs; }

Solution 3 - Using org.apache.http.client.utils.URLEncodedUtils

import org.apache.hc.client5.http.utils.URLEncodedUtils String url = "https://www.solutionfactory.in/data/authorize?id=kk&response_type=code&requestScope=FULL&Status=offline&redirect=http://www.solutionfactory.in"; List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), Charset.forName("UTF-8")); for (NameValuePair param : params) { System.out.println(param.getName() + " : " + param.getValue()); }
Follow Us, it encourages us to Help you Always.

Solution Worked 5 UpvotesUpvote

        

Solution Didn't Worked 2 DownvotesDownvote



Comments



Search

Play 2048 Game Online

Search Tags