Showing posts with label Encode. Show all posts
Showing posts with label Encode. Show all posts

Friday, 30 August 2013

Encode & Decode URL Parameters In Java

A small code example describing how to encode and decode URL query strings properly from Java. The code example is available from GitHub in the in the Java-Core-Examples directory.
String paramValue = "with spaces and special &!=; characters";

String encoded = URLEncoder.encode(paramValue, "UTF-8");
String decoded = URLDecoder.decode(encoded, "UTF-8");

System.out.println(paramValue);
System.out.println(encoded);
System.out.println(decoded);
The output is:
with spaces and special &!=; characters
with+spaces+and+special+%26%21%3D%3B+characters
with spaces and special &!=; characters

Friday, 10 August 2012

How to Encode and Decode Data to Base64 in Java?

In order to encode a string (or a byte array) into Base64, and then decode it into its original state, one can use the following piece of code:
String s = "String to encode/decode in Base64 with DataTypeConverter";

String coded = DatatypeConverter.printBase64Binary(s.getBytes());
byte[] retr = DatatypeConverter.parseBase64Binary(coded);

System.out.println("Coded     : " + coded);
System.out.println("Expected  : " + s);
System.out.println("Retrieved : " + new String(retr));
System.out.println();
The generated output is:
Coded     : U3RyaW5nIHRvIGVuY29kZS9kZWNvZGUgaW4gQmFzZTY0IHdpdGggRGF0YVR5cGVDb252ZXJ0ZXI=
Expected  : String to encode/decode in Base64 with DataTypeConverter
Retrieved : String to encode/decode in Base64 with DataTypeConverter

For input/output streams, one can use the following:
String s = "String to encode/decode in Base64 using streams";

ByteArrayOutputStream collect = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(collect);

b64os.write(s.getBytes());
b64os.close();

byte[] ba = collect.toByteArray();
String coded = new String(ba);

InputStream is = new ByteArrayInputStream(ba);
Base64InputStream b64is = new Base64InputStream(is);

byte[] retr = IOUtils.toByteArray(b64is);

System.out.println("Coded     : " + coded);
System.out.println("Expected  : " + s);
System.out.println("Retrieved : " + new String(retr));
The above uses an external library to convert the InputStream into a byte array. The generated output is:
Coded     : U3RyaW5nIHRvIGVuY29kZS9kZWNvZGUgaW4gQmFzZTY0IHVzaW5nIHN0cmVhbXM=
Expected  : String to encode/decode in Base64 using streams
Retrieved : String to encode/decode in Base64 using streams
The code examples are available from Github, in the Java-Core-Examples directory.

More Java tips & tricks here.