2

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.

2 Answers 2

2

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the code, but building my own function is exactly what I was trying to avoid.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.