Reputation: 308
we're looking for a standard way to encode a URL given a predefined base URL and a Map of parameters and values. Ideally the method is declarated as something like
String constructURL( String baseURL, Map<String,String> parameters)
would work like the following snippet
Map<String, String> params = new HashMap<String,String>();
params.put("p1", "v1");
params.put("p2", "v2");
String url = constructURL( "page.html", params);
and url would have the following value
"page.html?p1=v1&p2=v2"
Btw, we're using Apache Click with Tomcat.
Upvotes: 2
Views: 1081
Reputation: 1219
The JDK's URLEncoder
should work for your use case. Like this :
String constructURL(String base, Map<String, String> params) {
StringBuilder url = new StringBuilder(base);
if(params != null && params.size() > 0) {
url.append("?");
for(Map.Entry<String, String> entry : params.entrySet()) {
url.append(entry.getKey());
url.append("=");
url.append(URLEncoder.encode(entry.getValue()));
url.append("&"); //not for the last one (but should be OK)
}
}
return url.toString();
}
Upvotes: 2
Reputation: 11669
You can use URLCodec from Commons Codec to create the url-encoded version of your parameters, and then loop on the parameters to create the query. Have a look at the source of URLEncodedUtils class in Apache HttpClient to see an example of what I explain.
Upvotes: 1