Java URL Query Build getQueryString(final Map parameters, final boolean encode)

Here you can find the source of getQueryString(final Map parameters, final boolean encode)

Description

get Query String

License

Open Source License

Parameter

Parameter Description
parameters a parameter
encode a parameter

Exception

Parameter Description
UnsupportedEncodingException an exception

Return

String

Declaration

public static String getQueryString(final Map<String, Object> parameters, final boolean encode)
        throws UnsupportedEncodingException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Manchester Centre for Integrative Systems Biology
 * University of Manchester/*from  ww w.ja va2  s . co  m*/
 * Manchester M1 7ND
 * United Kingdom
 * 
 * Copyright (C) 2007 University of Manchester
 * 
 * This program is released under the Academic Free License ("AFL") v3.0.
 * (http://www.opensource.org/licenses/academic.php)
 *******************************************************************************/

import java.io.*;
import java.net.*;
import java.util.*;

public class Main {
    /**
     * 
     * @param parameters
     * @param encode
     * @return String
     * @throws UnsupportedEncodingException
     */
    public static String getQueryString(final Map<String, Object> parameters, final boolean encode)
            throws UnsupportedEncodingException {
        final String ENCODING = "UTF-8"; //$NON-NLS-1$
        final String EQUALS = "="; //$NON-NLS-1$
        final String AMPERSAND = "&"; //$NON-NLS-1$
        final String EQUALS_ENCODED = encode ? URLEncoder.encode(EQUALS, ENCODING) : EQUALS;
        final String AMPERSAND_ENCODED = encode ? URLEncoder.encode(AMPERSAND, ENCODING) : AMPERSAND;

        final StringBuffer queryString = new StringBuffer();

        for (Iterator<Map.Entry<String, Object>> iterator = parameters.entrySet().iterator(); iterator.hasNext();) {
            final Map.Entry<String, Object> entry = iterator.next();
            queryString.append(encode ? URLEncoder.encode(entry.getKey(), ENCODING) : entry.getKey());
            queryString.append(EQUALS_ENCODED);
            queryString.append(encode ? URLEncoder.encode(entry.getValue().toString(), ENCODING)
                    : entry.getValue().toString());
            queryString.append(AMPERSAND_ENCODED);
        }

        if (queryString.length() > 0) {
            queryString.setLength(queryString.length() - AMPERSAND_ENCODED.length());
        }

        return queryString.toString();
    }
}

Related

  1. getQueryParams(String httpUrl)
  2. getQueryParams(String query)
  3. getQueryParams(String s)
  4. getQueryParams(String url)
  5. getQueryString(final Map parameters)
  6. getQueryString(Map parameters)
  7. getQueryString(Map parameters)
  8. getQueryString(String url)
  9. getQueryUrl(String word)