Search code examples
javastandard-library

How to use java.net.URI


I've tried to use java.net.URI to manipulate query strings but I failed to even on very simple task like getting the query string from one url and placing it in another.

Do you know how to make this code below work

URI sample = new URI("test?param1=x%3D1");
URI uri2 = new URI(
            "http",
            "domain",
            "/a-path",
            sample.getRawQuery(),
            sample.getFragment());

Call to uri2.toASCIIString() should return: http://domain/a-path?param1=x%3D1 but it returns: http://domain/a-path?param1=x%253D1 (double encoding)

if I use getQuery() instead of getRawQuery() the query string is not encoded at all and the url looks like this: http://domain/a-path?param1=x=1


Solution

  • The problem is that the second constructor will encode the query and fragment using URL encoding. But = is a legal URI character, so it will not encode that for you; and % is not a legal URI character, so it will encode it. That's exactly the opposite of what you want, in this case.

    So, you can't use the second constructor. Use the first one, by concatenating the parts of the string together yourself.