Java URL Build queryStringToMap(String queryString, String charset)

Here you can find the source of queryStringToMap(String queryString, String charset)

Description

Convert a query string into a map.

License

Apache License

Parameter

Parameter Description
queryString the query string (e.g. a=b&c=d&e=f)
charset the character set for URLDecoder#decode(String,String) purposes

Return

a map representation of the query.

Declaration

public static Map<String, String> queryStringToMap(String queryString, String charset)
        throws UnsupportedEncodingException 

Method Source Code

//package com.java2s;
/*// w ww. j  a v a2s  .c om
 * Copyright 2017 Adaptris Ltd.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

import java.io.UnsupportedEncodingException;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class Main {
    /**
     * Convert a query string into a map.
     * 
     * @param queryString the query string (e.g. a=b&c=d&e=f)
     * @param charset the character set for {@link URLDecoder#decode(String, String)} purposes
     * @return a map representation of the query.
     */
    public static Map<String, String> queryStringToMap(String queryString, String charset)
            throws UnsupportedEncodingException {
        Map<String, String> result = new HashMap<>();
        String[] pairs = queryString.split("\\&");
        for (String pair : pairs) {
            StringTokenizer kp = new StringTokenizer(pair, "=");
            String key = kp.nextToken();
            String value = "true";
            if (kp.hasMoreTokens()) {
                value = URLDecoder.decode(kp.nextToken(), charset);
            }
            result.put(key, value);
        }
        return result;
    }
}

Related

  1. queryStringFromMap(Map map)
  2. queryStringify(HashMap qString)
  3. queryStringToMap(String query, Boolean decode)
  4. queryStringToMap(String queryString)
  5. queryStringToMap(String queryString, String charSet)
  6. queryToMap(final String query)
  7. queryToParams(String query)