Sunday, December 19, 2010

URL addresses with Special characters

Some URL addresses contain special characters, for example the space character. Like this:
http://foo.com/hello world/
To make theses characters legal they need to encoded before passing them to the URL constructor.
URL url = new URL("http://foo.com/hello%20world");
Encoding the special character(s) in this example is easy as there is only one character that needs encoding, but for URL addresses that have several of these characters or if you are unsure when writing your code what URL addresses you will need to access, you can use the multi-argument constructors of the java.net.URI class to automatically take care of the encoding for you.
URI uri = new URI("http", "foo.com", "/hello world/", "");
And then convert the URI to a URL.
URL url = uri.toURL();

No comments:

Post a Comment