memento
memento

Reputation: 319

How to encode an URL with Java

Given an URL such as this one,

http://www.example.com/some directory/some file

how do you encode this URL? Browsers automatically encode it. In Java I couldn't find a ready made function. I suspect there should be such a function because this is generally needed.

When I try to use the URI class using the constructor with single String, and parse components of the URL, such as authority, path, etc, it gives error because it expects an encoded URL.

Do you know a ready made function that will produce, for example in this case:

http://www.example.com/some%20directory/some%20file

Upvotes: 0

Views: 358

Answers (1)

Walery Strauch
Walery Strauch

Reputation: 7062

Try this:

final URL url = new URL("http://www.example.com/some directory/some file");
final URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), null);

System.out.println(uri.toASCIIString());

Upvotes: 4

Related Questions