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 = java.net.URLEncoder.encode( str, "UTF-8");
System.out.println(str);


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 = java.net.URLDecoder.decode( str, "UTF-8");
System.out.println(str);


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.

Comments

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: http://contextroot.blogspot.com/2012/04/encoding-urls-in-java-is-quite-trivial.html