What I\'m looking for specifically is some code in Java that will take a Map object and convert it into a query string that I can append to a URL I return. I\'
I found apache httpcomponents to be a solid and versatile library for dealing with HTTP in Java. However, here's a sample class, which might suffice for building URL query strings:
import java.net.URLEncoder;
public class QueryString {
private String query = "";
public QueryString(HashMap map) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
query += URLEncoder.encode(pairs.getKey(), "utf-8") + "=" +
URLEncoder.encode(pairs.getValue(), "utf-8");
if (it.hasNext()) { query += "&"; }
}
}
public QueryString(Object name, Object value) {
query = URLEncoder.encode(name.toString(), "utf-8") + "=" +
URLEncoder.encode(value.toString(), "utf-8");
}
public QueryString() { query = ""; }
public synchronized void add(Object name, Object value) {
if (!query.trim().equals("")) query += "&";
query += URLEncoder.encode(name.toString(), "utf-8") + "=" +
URLEncoder.encode(value.toString(), "utf-8");
}
public String toString() { return query; }
}
Usage:
HashMap map = new HashMap();
map.put("hello", "world");
map.put("lang", "en");
QueryString q = new QueryString(map);
System.out.println(q);
// => "hello=world&lang=en"