Tuesday, October 13, 2009

Use base64 in Android

In my Twitter Client application, I need a encoder for base64. There is a undocumented classes sun.misc.BASE64Encoder. But it's not suggested, because Developers Should Not Write Programs That Call 'sun' Packages.

Actually, I can't find anywhere to download sun.misc.BASE64Encoder. Somebody advise that it can be found in /jre/lib/rt.jar. I tried to add it to my build path, but my machine hang-up in build my project. So...I give-up sun.misc.BASE64Encoder finally.

Alternatively, there is a package, Commons Codec, from apache.org.

To use the Commons Codec, you have to download it from http://commons.apache.org/codec/download_codec.cgi, and save it to your local driver. The current version 1.4 that requires a minimum of JDK 1.4.

In Eclipse, right click your project > Build Path > Add External Archives >, browse to select the downloaded and extracted JAR.

The syntex to encode a input to base54 is:

import org.apache.commons.codec.binary.Base64;

String outputString = new String(Base64.encodeBase64(inputString.getBytes()));

Both inputString and outputString are in type String.

Actual usage in my Android Twitter Client.

1 comment:

ChmicalRomance said...

Thx. was great post!!
btw, I hav one question.
Do u know how to attach *.jar using relative path??
hmm... This is a group working. lol