Java URL Build buildQueryString(Map queryParams)

Here you can find the source of buildQueryString(Map queryParams)

Description

Builds a URI query string from a map of keys and values.

License

CDDL license

Parameter

Parameter Description
queryParams a map of keys and their values. A value may be a <code>List</code> for repeating values.

Return

the resulting query string

Declaration

public static String buildQueryString(Map<String, Object> queryParams) 

Method Source Code


//package com.java2s;
/*/*from  ww  w. j  a v a  2 s  .  c  om*/
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the "License").  You may not use this file except
 * in compliance with the License.
 * 
 * You can obtain a copy of the license at
 * http://www.opensource.org/licenses/cddl1.php
 * See the License for the specific language governing
 * permissions and limitations under the License.
 */

import java.io.UnsupportedEncodingException;

import java.util.List;
import java.util.Map;

public class Main {
    /**
     * Builds a URI query string from a map of keys and values.
     * @param queryParams a map of keys and their values. A value may be a <code>List</code> for repeating values.
     * @return the resulting query string
     */
    public static String buildQueryString(Map<String, Object> queryParams) {
        StringBuffer buf = new StringBuffer();
        boolean firstParam = true;
        try {
            for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
                if (entry.getValue() == null)
                    continue;
                if (entry.getValue() instanceof List<?>) {
                    List<?> values = (List<?>) entry.getValue();
                    for (Object value : values) {
                        if (!firstParam) {
                            buf.append('&');
                        }
                        buf.append(entry.getKey());
                        buf.append('=');
                        buf.append(java.net.URLEncoder.encode(value.toString(), "utf-8"));
                        firstParam = false;
                    }
                } else {
                    if (!firstParam) {
                        buf.append('&');
                    }
                    buf.append(entry.getKey());
                    buf.append('=');
                    buf.append(java.net.URLEncoder.encode(entry.getValue().toString(), "utf-8"));
                    firstParam = false;
                }
            }
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        return buf.toString();
    }
}

Related

  1. buildQuery(Map paramMap)
  2. buildQuery(Map query)
  3. buildQuery(Map params)
  4. buildQueryString(Map parameters)
  5. buildQueryString(Map params)
  6. buildQueryString(Map params)
  7. buildQueryString(Multimap params)
  8. buildURL(int imageId)
  9. buildUrl(String base, String local)