Java URL Parameter Builder mapToFormEncodedString(Map data)

Here you can find the source of mapToFormEncodedString(Map data)

Description

map To Form Encoded String

License

Open Source License

Declaration

private static String mapToFormEncodedString(Map<String, String> data) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.URLEncoder;
import java.util.ArrayList;

import java.util.List;
import java.util.Map;

public class Main {
    private static String mapToFormEncodedString(Map<String, String> data) {
        final List<String> acc = new ArrayList<String>();
        for (Map.Entry<String, String> entry : data.entrySet()) {
            acc.add(encodeURIComponent(entry.getKey()) + "=" + encodeURIComponent(entry.getValue()));
        }//from   w  w  w .  j av a 2 s. c  om
        return "?" + join(acc, "&");
    }

    private static String encodeURIComponent(String component) {
        String result;
        try {
            result = URLEncoder.encode(component, "UTF-8").replaceAll("%28", "(").replaceAll("%29", ")")
                    .replaceAll("\\+", "%20").replaceAll("%27", "'").replaceAll("%21", "!").replaceAll("%7E", "~");
        } catch (java.io.UnsupportedEncodingException e) {
            result = component;
        }
        return result;
    }

    public static String join(List<String> list, String separator) {
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (final String str : list) {
            if (first)
                first = false;
            else
                sb.append(separator);
            sb.append(str);
        }
        return sb.toString();
    }
}

Related

  1. getUrlParameters(String url)
  2. getUrlParameters(String url)
  3. getUrlParameters(String url)
  4. getURLParameters(URI uri)
  5. map2String(Map params)
  6. mapToFormString(Map map)
  7. mapToStr( Map map)
  8. mapToStr(Map map)
  9. mapToString(Map map)