Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 406
Piotr Czapla Avatar asked Sep 09 '11 13:09

Piotr Czapla


People also ask

What is Java Net URI?

A URI is a uniform resource identifier while a URL is a uniform resource locator. Hence every URL is a URI, abstractly speaking, but not every URI is a URL. This is because there is another subcategory of URIs, uniform resource names (URNs), which name resources but do not specify how to locate them.

What is URI and URL in Java?

URI is an acronym for Uniform Resource Identifier. URL is an acronym for Uniform Resource Locator. URI contains two subsets, URN, which tell the name, and URL, which tells the location. URL is the subset of URI, which tells the only location of the resource.

What is the use of Uri in spring boot?

Uniform Resource Identifier (URI) − a sequence of characters that allows the complete identification of any abstract or physical resource.


1 Answers

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.

like image 192
Jesper Avatar answered Oct 02 '22 16:10

Jesper