Saturday, August 15, 2009

Java: Urlencode and Urldecode options

Java has two different class Called URLDecoder, and URLEncoder which has decoder() and encoder() method respectively to decode and encode your URL for HTTP request. (I wonder why two separate classes? One would have been better I guess)

Lets say our initial string is
// our initial string
String str = "hello world and some & funny ?? Stuff++";

Now using encoder() function I'm encoding the string. The function is static, and it is available to access using the Class name URLEncoder.
// encoding the string using URLEncoder class
str = str, "UTF-8");

Now using decoder() method from URLDecoder class, I'm converting the encoded string into its previous form. This is also a static method, and possible to access via the class name.
// decoding the string using URLDecoder class
str = str, "UTF-8");

This will help you to encode your data before POST operation. Also At your web application the decoder will help your decode the data from POST request.

1 comment:

Anonymous said...

Should point out that URLEncoder and URLDecoder are not actually meant for handling URLs, despite their name, but form data.

Read this post if you wish to encode URLs with Java properly:

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...