Build an x-www-form-urlencoded query string from a map
Build an x-www-form-urlencoded query string from a map
Answer
StringBuilder q = new StringBuilder(); for (Map.Entry<String, String> e : params.entrySet()) { if (q.length() > 0) q.append('&'); q.append(URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8)); q.append('='); q.append(URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8)); }
Each key and each value is encoded on its own; the & and = that give the string its structure are appended raw. The Charset overload throws no checked exception, unlike the older String form, and UTF-8 is the only charset worth passing.
JDK javadoc java.net.URLEncoder