Data Encoding Tutorials - Herong's Tutorial Examples - v5.23, by Herong Yang
application/x-www-form-urlencoded Encoding in Java
This section provides a tutorial example on how to use Java URLEncoder class to perform application/x-www-form-urlencoded encoding and decoding.
Now let's see how we can do application/x-www-form-urlencoded encoding in Java language.
If you look at the java.net package, you will see two classes related to URL encoding:
java.net.URLEncoder - This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format. It offers this encoding method:
String encode(String s, "UTF-8") Translates a string into application/x-www-form-urlencoded format using "UTF-8" scheme.
java.net.URLDecoder - This class contains static methods for decoding a String from the application/x-www-form-urlencoded MIME format. It offers this decoding method:
String decode(String s, "UTF-8") Decodes an application/x-www-form-urlencoded string using using "UTF-8" scheme.
To test these classes, I wrote this tutorial example program:
/* WwwFormUrlencodedTest.java * Copyright (c) 2010 HerongYang.com. All Rights Reserved. */ import java.net.URLEncoder; import java.net.URLDecoder; class WwwFormUrlencodedTest { public static void main(String[] a) { if (a.length<1) { System.out.println("Usage:"); System.out.println("java WwwFormUrlencodedTest 1"); return; } String test = a[0]; String theInput = null; String theExpected = null; if (test.equals("1")) { theInput = "\u548c\u8363, how a u?"; theExpected = "%E5%92%8C%E8%8D%A3%2C+how+a+u%3F"; } else { System.out.println("Usage:"); System.out.println("java WwwFormUrlencodedTest 1"); return; } try { String theEncoded = URLEncoder.encode(theInput, "utf-8"); String theDecoded = URLDecoder.decode(theEncoded, "utf-8"); System.out.println("Input : "+theInput); System.out.println("Encoded : "+theEncoded); System.out.println("Expected: "+theExpected); System.out.println("Decoded : "+theDecoded); } catch (Exception e) { e.printStackTrace(); } return; } }
If you run this program in JDK 1.6, you should get:
Input : ??, how a u? Encoded : %E5%92%8C%E8%8D%A3%2C+how+a+u%3F Expected: %E5%92%8C%E8%8D%A3%2C+how+a+u%3F Decoded : ??, how a u?
The double-question-mark (??) is there because my Windows command line does not support Chinese characters.
Conclusion: Java URLEncoder and URLDecoder classes support application/x-www-form-urlencoded encoding and decoding.
Table of Contents
Base64 Encoding and Decoding Tools
Base64URL - URL Safe Base64 Encoding
►URL Encoding, URI Encoding, or Percent Encoding
URL Encoding on HTML Form Data - IE
URL Encoding on HTML Form Data - Firefox
►application/x-www-form-urlencoded Encoding in Java