Java URL Query Build createQueryString(Map params)

Here you can find the source of createQueryString(Map params)

Description

Given a java.util.Map of params, construct a query string

License

Open Source License

Parameter

Parameter Description
params a parameter

Declaration

public static String createQueryString(Map<String, String> params) 

Method Source Code

//package com.java2s;

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

import java.util.Map;

public class Main {
    /**/* w w  w. jav a  2  s  .c o  m*/
     * Given a {@link java.util.Map} of params, construct a query string
     *
     * @param params
     * @return
     */
    public static String createQueryString(Map<String, String> params) {
        StringBuilder queryString = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String paramName = entry.getKey();
            String paramValue = entry.getValue();
            if (first) {
                first = false;
            } else {
                queryString.append("&");
            }
            queryString.append(paramName).append("=");
            String encodedParamValue;
            try {
                if (paramValue == null)
                    throw new RuntimeException(
                            "paramValue is null for paramName=" + paramName);
                encodedParamValue = URLEncoder.encode(paramValue, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            queryString.append(encodedParamValue);
        }
        return queryString.toString();
    }
}

Related

  1. createQueryString(Map options)
  2. createQueryString(Map params)
  3. createQueryStringForParameters(Map parameters)
  4. createQueryStringFromMap(Map m, String ampersand, boolean encode)
  5. getQuery(Map params, String encode)
  6. getQuery(URL theURL)