Here you can find the source of parseQueryString(String path)
Parameter | Description |
---|---|
path | a url in the form path?k1=v1&k2=v2&,,, |
public static Map<String, Object> parseQueryString(String path)
//package com.java2s; /* (c) 2014 Open Source Geospatial Foundation - all rights reserved * (c) 2001 - 2013 OpenPlans//from w w w . j a v a 2s. c o m * This code is licensed under the GPL 2.0 license, available at the root * application directory. */ import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class Main { /** * Parses the parameters in the path query string. Normally this is done by the * servlet container but in a few cases (testing for example) we need to emulate the container * instead. * * @param path a url in the form path?k1=v1&k2=v2&,,, * @return */ public static Map<String, Object> parseQueryString(String path) { int index = path.indexOf('?'); if (index == -1) { return Collections.EMPTY_MAP; } String queryString = path.substring(index + 1); StringTokenizer st = new StringTokenizer(queryString, "&"); Map<String, Object> result = new HashMap<String, Object>(); while (st.hasMoreTokens()) { String token = st.nextToken(); String[] keyValuePair; int idx = token.indexOf('='); if (idx > 0) { keyValuePair = new String[2]; keyValuePair[0] = token.substring(0, idx); keyValuePair[1] = token.substring(idx + 1); } else { keyValuePair = new String[1]; keyValuePair[0] = token; } //check for any special characters if (keyValuePair.length > 1) { //replace any equals or & characters try { // if this one does not work first check if the url encoded content is really // properly encoded. I had good success with this: http://meyerweb.com/eric/tools/dencoder/ keyValuePair[1] = URLDecoder.decode(keyValuePair[1], "ISO-8859-1"); } catch (UnsupportedEncodingException e) { throw new RuntimeException( "Totally unexpected... is your JVM busted?", e); } } String key = keyValuePair[0]; String value = keyValuePair.length > 1 ? keyValuePair[1] : ""; if (result.get(key) == null) { result.put(key, value); } else { String[] array; Object oldValue = result.get(key); if (oldValue instanceof String) { array = new String[2]; array[0] = (String) oldValue; array[1] = value; } else { String[] oldArray = (String[]) oldValue; array = new String[oldArray.length + 1]; System.arraycopy(oldArray, 0, array, 0, oldArray.length); array[oldArray.length] = value; } result.put(key, array); } } return result; } }