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

Java examples for Network:URL

Description

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

Demo Code


//package com.java2s;

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

import java.util.Map;

public class Main {
    /**/*ww  w. ja  v a2 s  . co  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 Tutorials