集册 Java实例教程 给定参数的java.util.Map,构造一个查询字符串

给定参数的java.util.Map,构造一个查询字符串

欢马劈雪     最近更新时间:2020-01-02 10:19:05

539
给定参数的java.util.Map,构造一个查询字符串
/** 时代Java公众号 - N o w J a  v a . c o m 提 供 **/

//package com.nowjava;


import java.io.UnsupportedEncodingException;


import java.net.URLEncoder;


import java.util.Map;


public class Main {

    /**

     * 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()) {
        /* 
        *来 自
         时代Java
        */

            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");

展开阅读全文