construct Parameter Map from URL query - Java java.util

Java examples for java.util:Map Creation

Description

construct Parameter Map from URL query

Demo Code


import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class Main{
    public static void main(String[] argv){
        String queryString = "book2s.com";
        System.out.println(constructParamMap(queryString));
    }/*from  ww  w.  j a va2  s  .  c om*/
    public static Map<String, String> constructParamMap(
            final String queryString) {

        if (!StringUtils.isSet(queryString)) {
            return new LinkedHashMap<String, String>();
        }

        final Map<String, String> paramMap = new LinkedHashMap<String, String>();
        final String[] pairs = queryString.split("&");
        for (final String pair : pairs) {
            final String[] splittedPair = pair.split("=");

            final String splittedPairKey = splittedPair[0];
            String splittedPairValue = splittedPair.length > 1 ? splittedPair[1]
                    : "";

            if (StringUtils.isWithinSquareBrackets(splittedPairValue)) {

                final String cleansedValue = StringUtils
                        .decodeUrlEncodedQuotes(StringUtils
                                .removeSquareBrackets(splittedPairValue));
                final String bracketedQueryValueAsCSV = Arrays.asList(
                        cleansedValue.split(",")).toString();
                splittedPairValue = StringUtils
                        .trimSpacesBetweenCSVElements(bracketedQueryValueAsCSV);
            }

            paramMap.put(splittedPairKey, splittedPairValue);
        }

        return paramMap;
    }
}

Related Tutorials