Java API/util to find and replace unsafe characters with their percent encoded forms?

957 Views Asked by At

Does anyone know of a decent Java API/util to find and replace unsafe characters in a URL with their percent-encoded forms?

2

There are 2 best solutions below

0
On
"http://google.com?" + URLEncoder.encode("...", "UTF-8");

See javadocs.

One should add the expected character encoding.

0
On

See Java - Convert String to valid URI object for pure Java style:

String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();

Beware that it handles protocols available to Java natively. Otherwise you may need to register your own one like "s3" for Amazon S3 URIs.