Parsing Query Strings in Java and accessing values by key
First, you require http://hc.apache.org/, specifically httpclient-4.1.3.jar and httpcore-4.1.3.jar. Then two classes:
NameValuePairComparator.java
import java.util.Comparator; import org.apache.http.NameValuePair; public class NameValuePairComparator implements Comparator { @Override public int compare(NameValuePair arg0, NameValuePair arg1) { return arg0.getName().compareTo(arg1.getName()); } }
QueryParamList.java
import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; public class QueryParamList { private List params; private boolean sorted = false; NameValuePairComparator comparator = new NameValuePairComparator(); public QueryParamList(List params) { setParams(params); } protected void sort() { Collections.sort(params,comparator); sorted=true; } @SuppressWarnings({ "unchecked", "rawtypes" }) public String get(String key) { if (!sorted) { sort(); } int index = Collections.binarySearch((List<NameValuePair>) getParams(), (Object) new BasicNameValuePair(key,null) , (Comparator) comparator); if (index <= 0) { return params.get(index).getValue(); } else { return null; } } public List getParams() { return params; } public void setParams(List params) { this.params = params; } }
Example:
URI uri = new URI("http://go.com?a=1"); QueryParamList params = new QueryParamList(URLEncodedUtils.parse(uri, "UTF-8")); String a = params.get("a");