convert Map<String,String> To URL query String - Java java.net

Java examples for java.net:URL Query

Introduction

The following code shows how to convert To String

Demo Code

public class Main {
  public static String convertToString(java.util.Map<String, Object> properties) {
    java.util.List<String> parts = new java.util.ArrayList<String>();
    for (String key : properties.keySet()) {
      Object value = properties.get(key);
      if (value instanceof String) {
        parts.add(encode('=', new String[] { key, (String) value }));
      } else {/*  w w w.j a  v a  2s .  c  om*/
        throw new RuntimeException("Can't encode " + value);
      }
    }
    return encode(';', parts);
  }

  public static String encode(char delimiter, String[] parts) {
    java.util.List<String> partList = new java.util.ArrayList<String>();
    for (String part : parts) {
      partList.add(part);
    }
    return encode(delimiter, partList);
  }

  public static String encode(char delimiter, Iterable<String> parts) {
    StringBuilder result = new StringBuilder();
    for (String part : parts) {
      String encodedPart = part.replace("\\", "\\\\");
      encodedPart = encodedPart.replace("" + delimiter, "\\" + delimiter);
      result.append(encodedPart);
      result.append(delimiter);
    }
    return result.toString();
  }

}

Related Tutorials