Saturday, February 9, 2008

Encoding the Request Parameters

Recently I just faced some problem with Ajax implementation, here is an answer I found for the problem:

"When developing a traditional Web application you don't have to worry about encoding the form data because the Web browser performs this operation automatically when the user submits the data. In the case of an Ajax application, however, it's your job to encode the request parameters. JavaScript provides a very useful function named escape() that replaces any character that cannot be part of a URL with %HH where HH is the hexadecimal code. For example, any space character is replaced with %20."

The problem is very simple, when we make a http call to any url, we should encode the request parameters. I think I faced this similar problem when doing J2ME http call as well.

This code when make a http call, the result url will become:
http://www.abc.com/testing.asp?title=Title 1&content=Content body

Do you notice what problem with this url? Ya, the white space. From server side, the title & content text will received wrongly. (White space missing)
In order to correct it, we must add an encode function to replace the special text (white space) to "%20" or "+".
http://www.abc.com/testing.asp?title=Title+1&content=Content+body
http://www.abc.com/testing.asp?title=Title%201&content=Content%20body

Then only we can receive the correct text from the http call.

Another half day gone.

Here some special text that might be useful:
1) White space - %20
2) New line - %0D%0A (Windows), %0A (Unix), %0D (Macintosh)
3) "+" - %2B
4) "/" - %2F

No comments:

Post a Comment