I have a Map with my data and want to build a query string with it, just like I would with http_build_query on PHP. I’m not sure if this code is the best implementation of it or if I’m forgetting something?
public String toQueryString(Map<?, ?> data) throws UnsupportedEncodingException { StringBuffer queryString = new StringBuffer(); for (Entry<?, ?> pair : data.entrySet()) { queryString.append ( URLEncoder.encode ( (String) pair.getKey (), 'UTF-8' ) + '=' ); queryString.append ( URLEncoder.encode ( (String) pair.getValue (), 'UTF-8' ) + '&' ); } if (queryString.length () > 0) { queryString.deleteCharAt ( queryString.length () - 1 ); } return queryString.toString (); }
look at the QueryStringBuilder class and its test class :