Friday, June 12, 2015

Things to remember when encoding query strings

Encoding parameters in a Url is a very common situation but there is one important tip to remember. This is when you are encoding query strings that you would probably retrieve from 'request.parameter()' at some point. Let us look at an example first.

Say you need  to add few query strings to a url and encode it.  If you encode like below,
valueOfa="this is a";
valueOfb = "this is b";
String parameters = URLEncoder.encode("a=" + valueOfa + "&b=" + valueOfb);

you will finally get your queries in a url like this.

....a%3Dthis+is+a%26b%3Dthis+is+b

So what happens here, when encoding URLEncoder encodes blindly. It will encode your spaces as well as your '=' and '&' which you really do not need to encode as well. So basically at this point you can't retrieve your query values, since there is noway to distinguish the parameters(a,b) or their values.

The solution to this is, encode your queries, and construct each section at a time. See below.

String parameters = URLEncoder.encode("a");
parameters +=  "=";
parameters += URLEncoder.encode(valueOfa);
parameters += "&";
parameters +=  URLEncoder.encode("b");
parameters +=  "=";
parameters += URLEncoder.encode(valueOfb);

So this way, your query strings will appear in the url like below.

...a=this+is+a&b=this+is+b

You could check this link for more important tips on encoding and decoding.  http://www.onjava.com/excerpt/jvntwkprg_3e/index.html

No comments:

Post a Comment