The example below encode a URL string. Be sure to check java docs as each library handles escaping URLs is similar but different. In the set up method we will reference a URI that each of the snippet will use.
Setup
Straight up Java
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. In this example we want to encode the URL not form encoding using java. This method doesn't lend itself to be reusable unless you are going to wrap the method that performs this behavior already.
Google Guava
Using guava Escaper we will show how to escape url parameters by calling UrlEscapers.urlPathSegmentEscaper(). This method will escape strings so they can be used within a URL path.
Apache Commons
Using apache common's URLCodec we will call encode method which will encodes a string into its URL safe form.
Spring Framework
In this snippet we will encodes the given URI path string so it is safe to be used within a given URL using Springframework. If you are using Java 7 you can use StandardCharsets OR use Guava Charsets. It is quite possible that the Guava Charset version could become deprecated in future releases.