~/ learn/ comp-348/ cards/ Equality, the URI class, and form encoding
1 of 4

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

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/2d336e2b-f207-45d8-b1b5-00f8662b168d/flashcard utf-8 LF