40

I need to do a few very simple URL manipulations in Java. Like get the value for a parameter in the query, or update it, ... I was expecting to find a simple utility class doing that in the commons-lang package, but no. I know it is a simple problem, but if there is something already written, why do it again ? Do you know of any ?

I would like to have at least the following capabilities :

String myUrl = "http://www.example.com/test.html?toto=1&titi=2";

// get the value of a parameter
String parameterValue = UrlUtils.getParameterValue(myUrl, "toto");
Assert.equals(parameterValue, "1");

// update a parameter
String newUrl = UrlUtils.updateParameter(myUrl, "toto", 3);
parameterValue = UrlUtils.getParameterValue(myUrl, "toto");
Assert.equals(parameterValue, "3");

Ideally, it would take care of all encoding related issues, and work with java.net.Url as well as with Strings.

Thanks for your help !

Guillaume
  • 18,494
  • 8
  • 53
  • 74

3 Answers3

7

I think what you want is called a query string parser instead of an url manipulator and here's one: http://ostermiller.org/utils/CGIParser.java.html

Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
  • 1
    Unfortunately, that lib seems to disallow null values. These may be two distinct queries in some apps: `?foo` and `?foo=`. – Tim has moved to Codidact Jul 09 '13 at 13:56
  • Please check this solution as I do believe it is perhaps a more mainstream library and does what the OP asked: http://stackoverflow.com/a/37744000/1882064 – arcseldon Jun 10 '16 at 08:57
4

Apache's httpcomponents library has a URL decoder: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html

Httpcomponents is the successor to commons http client.

piepera
  • 2,033
  • 1
  • 20
  • 21
3

Indeed has released an efficient Java library for query string and number parsing:

http://engineering.indeed.com/blog/2014/02/efficient-query-string-parsing-util-urlparsing/

https://github.com/indeedeng/util/tree/master/urlparsing

(Disclaimer: I am an engineering director at Indeed.)