Java URL Query Build getQueryString(Map parameters)

Here you can find the source of getQueryString(Map parameters)

Description

Gets a valid query-string based on the given parameters.

License

Apache License

Declaration

public static String getQueryString(Map<String, String> parameters) 

Method Source Code


//package com.java2s;
/* 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
 * //from  w  w  w. j a v a  2s  .  c o m
 *      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 PARAMETER_SEPARATOR = "&";
    private static final String QUERY_STRING_SEPARATOR = "?";
    private static final String NAME_VALUE_SEPARATOR = "=";

    /**
     * Gets a valid query-string based on the given parameters.
     */
    public static String getQueryString(Map<String, String> parameters) {
        StringBuilder result = new StringBuilder();

        if (parameters != null) {
            for (Entry<String, String> param : parameters.entrySet()) {
                final String encodedName = encode(param.getKey(), null);
                final String value = param.getValue();
                final String encodedValue = value != null ? encode(value, null) : "";
                if (result.length() > 0) {
                    result.append(PARAMETER_SEPARATOR);
                } else {
                    result.append(QUERY_STRING_SEPARATOR);
                }
                result.append(encodedName);
                result.append(NAME_VALUE_SEPARATOR);
                result.append(encodedValue);
            }
        }

        return result.toString();
    }

    public 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. getQueryParams(String s)
  2. getQueryParams(String url)
  3. getQueryString(final Map parameters)
  4. getQueryString(final Map parameters, final boolean encode)
  5. getQueryString(Map parameters)
  6. getQueryString(String url)
  7. getQueryUrl(String word)
  8. getQueryUrl(String word, Integer page)
  9. getQueryURL(URL baseUrl, String[] parameters)