Canonicalize a Map as a query string. - Java java.util

Java examples for java.util:Map Operation

Description

Canonicalize a Map as a query string.

Demo Code


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main{
    /**/*from  ww  w.j a v a2  s.  c  o m*/
     * Canonicalize a Map as a query string.
     *
     * @param params Parameter name-value pairs.
     * @return Canonical form of query string. May be an empty string, but never null.
     */
    public static String mapToQueryString(final Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return "";
        }

        final StringBuilder buffer = new StringBuilder(350);
        final Iterator<Map.Entry<String, String>> iter = params.entrySet()
                .iterator();

        while (iter.hasNext()) {
            final Map.Entry<String, String> pair = iter.next();
            buffer.append(StringUtils.percentEncodeRfc3986(pair.getKey()));
            buffer.append('=');
            buffer.append(StringUtils.percentEncodeRfc3986(pair.getValue()));
            if (iter.hasNext()) {
                buffer.append('&');
            }
        }

        return buffer.toString();
    }
}

Related Tutorials