Thursday 14 May 2009

Java URLEncode

After working on an android project for Google's G1 phone I came across a problem using the java.net.URLEncoder class whereby it was not correctly encoding 3 values in conformance to the RFC 3986. The function URLEncoder.encode(s, enc) does not encode *, ~ or + (asterisk, tilde and plus) which was causing trouble when accessing particularly picky web services with strict definitions on content encoding. So with a bit of botchery you can make the string compliant by encoding them seperately using java Strings built in replace method. The example below shows a bare bones example of encoding a value.


String value = "beans+pies*with~fries"; // Mind the awful scentence
String encoded = URLEncoder.encode(value, "UTF-8");
encoded = encoded.replace("*", "%2A");
encoded = encoded.replace("~", "%7E");
encoded = encoded.replace("+", "%20");
// The output is "beans%20pies%2Awith%7Efries" all done!

3 comments:

  1. Nice one! Keep up the good work.

    ReplyDelete
  2. The RFC actually says that tildes don't need to be encoded. Unfortunately, URLEncoder encodes them anyway (and so do you apparently).

    ReplyDelete