Wednesday, July 13, 2011

Append parameters to URL String in java

Suppose you have a URL string as You would like to add and remove parameters to this URL. Also, you would like to encode these parameters so that they are HTTP safe (for example replace blank space with %20). One way is to do String concatenation, which is so like not java. I have written a Java helper class to perform this operation conveniently. You need to instantiate this class by passing the base URL as constructor parameter (eg: Then call the put() method to add param name and param values. You can call this method multiple times depending on the number of parameters. In the end, just call the toURL() method and get the desired URL object.

Note: You would need Apache commons lang library ( for this code

The class name is HttpUrlBuilder

 ** Author:
 ** onlyjavablog[AT]gmail[DOT]com
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class HttpUrlBuilder {
 private URL baseUrl;
 private StringBuilder baseUrlStr;
 private Map paramsMap;
 private boolean isFirstAdd = true;
 private static final String QUESTION_MARK = "?";
 private static final String EQUAL = "=";
 private static final String AMPERSAND = "&";
 private static final String UTF_8 = "UTF-8";
 public HttpUrlBuilder(URL baseUrl) throws MalformedURLException {
  if(baseUrl == null)
   throw new MalformedURLException("Null URL passed in constructor");
  String str = baseUrl.toString();
   throw new MalformedURLException("String Value of Url was blank.");
  this.baseUrl = baseUrl;
  this.baseUrlStr = new StringBuilder(str);
  paramsMap = new HashMap();
 public void put(String name, String value) {
  paramsMap.put(name, value);
 public void remove(String name) {
 public URL toUrl() throws MalformedURLException {
  Iterator it = paramsMap.keySet().iterator();
  while(it.hasNext()) {
   String key =;
   String value = paramsMap.get(key);
   if(isFirstAdd) {
    isFirstAdd = false;
    if(baseUrlStr.indexOf(QUESTION_MARK) < 1) {
     //does not contain "?"
     encode(key, value);
    } else {
     //contains "?"
     encode(key, value);
   } else {
    encode(key, value);
  URL retVal = new URL(baseUrlStr.toString());
  baseUrlStr = new StringBuilder(baseUrl.toString());
  isFirstAdd = true;
  return retVal;
 private void encode(String name, String value) {
   baseUrlStr.append(URLEncoder.encode(name, UTF_8));
   baseUrlStr.append(URLEncoder.encode(value, UTF_8));
  } catch (UnsupportedEncodingException  uee) {
   throw new RuntimeException("VM does not support UTF-8 encoding");
Usage of this class goes like this:
HttpUrlBuilder urlBuilder = new HttpUrlBuilder(new URL(""));

URL url = urlBuilder.toUrl();

The result is:

Related Posts:

No comments:

Post a Comment