简体   繁体   中英

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

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?

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();

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.

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().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM