Question

Is there an equivalent library for parsing url query params in java?

In order to illustrate what i want i send a code example:

use URI;
use URI::QueryParam;

$u = URI->new("http://www.google.com?a=b&c=d");
print $u->query,"\n";    # prints foo=1&foo=2&foo=3

for my $key ($u->query_param) {
    print "$key: ", join(", ", $u->query_param($key)), "\n";
}

The output is:

a=b&c=d

a: b

c: d

I don't like to write my own functions of query fragment parsing.

Was it helpful?

Solution

Not exactly that but close to:

final URI uri = URI.create(inputString);
final String[] queryParams = uri.getQuery().split("&");

You'd then split again on "=" each of the elements of queryParams.


NOTE: do NOT use URLDecoder directly to decode the values of query fragments; it will turn + into spaces, which is wrong according to the URI spec (pchar contains sub-delim contains +!)

An approaching solution would be to:

URLDecoder.decode(param.replace("+", "%2b"), "UTF-8")

To encode, use Guava's UrlPathSegmentEscaper.

Demonstration: this simple main:

public static void main(final String... args)
    throws UnsupportedEncodingException, URISyntaxException
{
    System.out.println(URLDecoder.decode("a+b", "UTF-8"));
    System.out.println(new URI("http", "foo.bar", "/baz", "op=a+b", null));
    System.out.println(new URI("http", "foo.bar", "/baz", "op=a b", null));
}

prints:

a b // WRONG!
http://foo.bar/baz?op=a+b
http://foo.bar/baz?op=a%20b

OTHER TIPS

What's wrong with java.net.URL and java.net.URI?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top