Java URL Query Parse parseQueryString(String path)

Here you can find the source of parseQueryString(String path)

Description

Parses the parameters in the path query string.

License

Open Source License

Parameter

Parameter Description
path a url in the form path?k1=v1&k2=v2&,,,

Declaration

public static Map<String, String> parseQueryString(String path) 

Method Source Code

//package com.java2s;
/* Copyright (c) 2001 - 2007 TOPP - www.openplans.org.  All rights reserved.
 * This code is licensed under the GPL 2.0 license, availible at the root
 * application directory.// w w  w  . ja v  a  2 s .  c  om
 */

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, String> 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, String> result = new HashMap<String, String>();
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            String[] keyValuePair = token.split("=");

            //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);
                }

            }

            result.put(keyValuePair[0],
                    keyValuePair.length > 1 ? keyValuePair[1] : "");
        }

        return result;
    }
}

Related

  1. parseQuery(String queryString)
  2. parseQueryParameters( String query)
  3. parseQueryParameters( String queryString, String encoding)
  4. parseQueryString(final String newQueryString, final String encoding)
  5. parseQueryString(String input)
  6. parseQueryString(String path)
  7. parseQueryString(String q, String enc)
  8. parseQueryString(String query)
  9. parseQueryString(String query)