Extract a map from a URL query string. - Java Network

Java examples for Network:URL

Description

Extract a map from a URL query string.

Demo Code


import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;

public class Main{
    public static void main(String[] argv) throws Exception{
        String query = "java2s.com";
        System.out.println(extractMap(query));
    }//  w  w  w  .ja va2 s . c o m
    /**
     * Extract a map from a query string.
     * 
     * @param query a query (or fragment) string from a URI
     * @return a Map of the values in the query
     */
    public static Map<String, String> extractMap(String query) {
        Map<String, String> map = new HashMap<String, String>();
        Properties properties = StringUtils
                .splitArrayElementsIntoProperties(
                        StringUtils.delimitedListToStringArray(query, "&"),
                        "=");
        if (properties != null) {
            for (Object key : properties.keySet()) {
                map.put(key.toString(), properties.get(key).toString());
            }
        }
        return map;
    }
}

Related Tutorials