Wednesday, July 21, 2010

Encode / decode parameters for GET request

As is well-known GET request parameters (query string) must be encoded on client-side and decoded on server-side. Normally an application server is responsible for decoding URL parameters. But in the real world I already had a case where parameters were not decoded (maybe some settings were wrong). Well. The client-side solution which I wrote for my web apps is to pass request parameters through this function
// Replaces all special characters in the passed string.
function encodeString(thestring)
{
    var encodedValue;
    if(window.encodeURIComponent) {
        encodedValue = encodeURIComponent(thestring);
    } else {
        encodedValue = escape(thestring);
        encodedValue = encodedValue.replace(new RegExp('\\+', 'g'), '%2B');
    }
    return encodedValue;
}
The Java based server-side solution (if needed) is easy.
String encoding = request.getCharacterEncoding();
if (encoding == null) {
    encoding = "UTF-8";
}

try {
    String decodedParameter = java.net.URLDecoder.decode(originalParameter, encoding);
    ...
} catch (UnsupportedEncodingException e) {
    // do something
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.