Java URL Parameter Builder format(final Map> parameters, final String encoding)

Here you can find the source of format(final Map> parameters, final String encoding)

Description

Returns a String that is suitable for use as an application/x-www-form-urlencoded list of parameters in an HTTP PUT or HTTP POST.

License

Open Source License

Parameter

Parameter Description
parameters The parameters to include.
encoding The encoding to use.

Declaration

public static String format(final Map<String, Set<String>> parameters, final String encoding) 

Method Source Code


//package com.java2s;
import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;
import java.util.*;

public class Main {
    private static final String PARAMETER_SEPARATOR = "&";
    private static final String NAME_VALUE_SEPARATOR = "=";

    /**/* w  w  w . j a v  a 2 s.co m*/
     * Returns a String that is suitable for use as an <code>application/x-www-form-urlencoded</code>
     * list of parameters in an HTTP PUT or HTTP POST.
     *
     * @param parameters
     *         The parameters to include.
     * @param encoding
     *         The encoding to use.
     */
    public static String format(final Map<String, Set<String>> parameters, final String encoding) {
        final StringBuilder result = new StringBuilder();

        for (Map.Entry<String, Set<String>> parameter : parameters.entrySet()) {
            final String encodedName = encode(parameter.getKey(), encoding);
            final Set<String> values = parameter.getValue();
            if (values == null || values.size() == 0) {
                result.append(encodedName);
                result.append(NAME_VALUE_SEPARATOR);
                result.append("");
            } else {
                for (String value : values) {
                    final String encodedValue = value != null ? encode(value, encoding) : "";
                    if (result.length() > 0)
                        result.append(PARAMETER_SEPARATOR);
                    result.append(encodedName);
                    result.append(NAME_VALUE_SEPARATOR);
                    result.append(encodedValue);
                }
            }
        }
        return result.toString();
    }

    private static String encode(final String content, final String encoding) {
        try {
            return URLEncoder.encode(content, encoding != null ? encoding : "UTF-8");
        } catch (UnsupportedEncodingException problem) {
            throw new IllegalArgumentException(problem);
        }
    }
}

Related

  1. constructParameterString(TreeMap pPostParms)
  2. convertHttpParameters(Map parameters)
  3. convertToDataString(Map data)
  4. convertToParameterString(Map parameterMap)
  5. extractParameters(String parameterString)
  6. format(Map parameters, final String encoding)
  7. getParameter(String source, int index)
  8. getParameterMap(byte[] bytea)
  9. getParams(String str)