Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can escape URL in Java (docs are not clear)?

Tags:

java

url

escaping

I have found various posts where escaping in Java is done with java.net.URLEncoder.encode. However I have found in docs for URL that:

The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396.

Can someone explain me this situation?

like image 368
Čikić Nenad Avatar asked Oct 28 '12 06:10

Čikić Nenad


3 Answers

You can use URI. For example:

URI uri = new URI("http","google.com","/ a z.html","asd= z%#@@#");
System.out.println(uri.toString());
//returns http://google.com/%20a%20z.html#asd=%20z%25%23@@%23

note that the single parameter constructor does not escape characters, so it'll throw an exception if you do something like:

URI uri = new URI("http://google.com/ a z.html?asd= z%#@@#");

From a URI you can get a URL by doing:

URL uri.toURL();
like image 153
Alon Bar David Avatar answered Sep 22 '22 08:09

Alon Bar David


The document correctly advises to use the URI class. The reason URLEncoder is still mentioned is I guess historical cause URLEncoder has been there since 1.0 while URI was added in 1.4.

like image 23
Eelke Avatar answered Sep 22 '22 08:09

Eelke


URLEncoder, despite its name, is for encoding URL arguments or POST parameters.

The correct way to encode URLs proper, before the query string, is via new URI(null, String, null).toURL().

like image 28
user207421 Avatar answered Sep 23 '22 08:09

user207421