Java URL Parameter Builder mapToStr( Map map)

Here you can find the source of mapToStr( Map map)

Description

Creates an encoded String from a Map of name/value pairs (MUST BE STRINGS!)

License

Apache License

Parameter

Parameter Description
map The Map of name/value pairs

Return

String The encoded String

Declaration

public static String mapToStr(
        Map<? extends Object, ? extends Object> map) 

Method Source Code

//package com.java2s;
/*/*from  w  w  w .  j  a v a2 s .  co m*/
 * Copyright 2001-2006 The Apache Software Foundation
 *
 * 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;

public class Main {
    /**
     * Creates an encoded String from a Map of name/value pairs (MUST BE STRINGS!)
     * @param map The Map of name/value pairs
     * @return String The encoded String
     */
    public static String mapToStr(
            Map<? extends Object, ? extends Object> map) {
        if (map == null)
            return null;
        StringBuilder buf = new StringBuilder();
        boolean first = true;

        for (Map.Entry<? extends Object, ? extends Object> entry : map
                .entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();

            if (!(key instanceof String) || !(value instanceof String))
                continue;
            String encodedName = null;
            try {
                encodedName = URLEncoder.encode((String) key, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String encodedValue = null;
            try {
                encodedValue = URLEncoder.encode((String) value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            if (first)
                first = false;
            else
                buf.append("|");

            buf.append(encodedName);
            buf.append("=");
            buf.append(encodedValue);
        }
        return buf.toString();
    }
}

Related

  1. getUrlParameters(String url)
  2. getURLParameters(URI uri)
  3. map2String(Map params)
  4. mapToFormEncodedString(Map data)
  5. mapToFormString(Map map)
  6. mapToStr(Map map)
  7. mapToString(Map map)
  8. parse(final Map> parameters, final Scanner scanner, final String encoding)
  9. parse_parameters(String input)