Java URI Create addParameters(Map parameters, StringBuilder uri)

Here you can find the source of addParameters(Map parameters, StringBuilder uri)

Description

Add parameters to the uri.

License

Apache License

Parameter

Parameter Description
parameters The parameters to add.
uri The builder that will receive the encoded parameters.

Declaration

public static void addParameters(Map<String, String> parameters, StringBuilder uri) 

Method Source Code

//package com.java2s;
/**/* w ww  . j ava 2 s.  co m*/
 * Copyright 2012-, Cloudsmith Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not
 * use this file except in compliance with the License. You may obtain a copy
 * of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

import java.util.Map;
import java.util.Map.Entry;

public class Main {
    private static final String QUERY_ENCODING = "UTF-8";

    /**
     * Add parameters to the <code>uri</code>. The parameters will be encoded.
     * 
     * @param parameters The parameters to add.
     * @param uri The builder that will receive the encoded parameters.
     */
    public static void addParameters(Map<String, String> parameters, StringBuilder uri) {
        if (parameters == null || parameters.isEmpty())
            return;
        for (Entry<String, String> param : parameters.entrySet())
            addParameter(param.getKey(), param.getValue(), uri);
    }

    public static void addParameter(String name, String value, StringBuilder uri) {
        if (uri.length() > 0)
            uri.append('&');
        uri.append(encode(name));
        if (value != null) {
            uri.append('=');
            uri.append(encode(value));
        }
    }

    /**
     * Encode a value using the URLEncoder and UTF-8
     * 
     * @param value The value to encode
     * @return The encoded value.
     */
    public static String encode(String value) {
        try {
            return URLEncoder.encode(value, QUERY_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

Related

  1. addParameter(String name, String value, StringBuilder uri)
  2. addParams(final Map params, final StringBuilder uri)
  3. addParams(URI uri, Map> params, Set overridenParams)
  4. addQueryParametersToUri(URI uri, Map parameters)
  5. addQueryParamsToUri(String uri, Map queryParams)