Wednesday, July 13, 2011

Append parameters to URL String in java

Suppose you have a URL string as http://www.mydomain.com. 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: http://www.mydomain.com). 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 (http://commons.apache.org/lang/download_lang.cgi) for this code

The class name is HttpUrlBuilder

/**
 ** Author: http://only-java.blogspot.com
 ** onlyjavablog[AT]gmail[DOT]com
 **/
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
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();
  if(StringUtils.isBlank(str))
   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) {
  paramsMap.remove(name);
 } 
 
 public URL toUrl() throws MalformedURLException {
  Iterator it = paramsMap.keySet().iterator();
  while(it.hasNext()) {
   String key = it.next();
   String value = paramsMap.get(key);
   if(isFirstAdd) {
    isFirstAdd = false;
    if(baseUrlStr.indexOf(QUESTION_MARK) < 1) {
     //does not contain "?"
     baseUrlStr.append(QUESTION_MARK);
     encode(key, value);
    } else {
     //contains "?"
     baseUrlStr.append(AMPERSAND);
     encode(key, value);
    }    
   } else {
    baseUrlStr.append(AMPERSAND);
    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) {
  try{
   baseUrlStr.append(URLEncoder.encode(name, UTF_8));
   baseUrlStr.append(EQUAL);
   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("http://www.mydomain.com"));
urlBuilder.put("firstName","Rachel");
urlBuilder.put("lastName","smith");
urlBuilder.put("age","28");
...
...

URL url = urlBuilder.toUrl();

System.out.println(url.toString());
The result is: http://www.mydomain.com?firstName=Rachel&age=28&lastName=smith

Related Posts:


No comments:

Post a Comment