URL encode and decode a String using Apache Commons

This code example will show how to URL encode and decode a String value using the Apache Commons Codec library.

The class URLCodec can encode a String value using different charsets. Either we can specify a charset to an overloaded constructor, or to an overloaded version of the method encode. In this case however, we’ll just use the default constructor without parameters and display the default charset.

In the example we use a String with “%” and “&” characters to show how these will be encoded. After the String has been encoded we decode it back to the original value and print out both values.

Output:

As we can see the default charset is UTF-8 and the characters “%” and “&” are encoded.

Base64 encoding and decoding using Apache Commons

This code example shows how to encode a String in Base64 and then decode it back to a readable String again.
The class Base64 have both static methods and non-static methods to do the encoding and decoding. The class also have several constructors for different features and first we will use the default constructor without parameters to do our base64 encoding / decoding.

Continue reading