14 March 2010

URL Decoding revisited

Time to complete the set. So far in this series I have presented URIEncode, URIDecode and URIEncodeQueryString. So here's the missing piece of the jigsaw: URIDecodeQueryString. This routine decodes a query string that has been "query-string-encoded".

If you look at URL Encoding revisited you'll see that a query string is encoded with normal URI encoding, except that space characters are encoded using '+' characters instead of '%20'.

So, to decode a query string we first need to replace literal '+' characters with spaces. Because the string is still URI encoded we should replace ocurrences of '+' with '%20', not the actual space character. Once this is done we are left with a standard URI encoded string which we decode as normal. Here's the code:

function URIDecodeQueryString(const Str: string): string;
begin
  Result := URIDecode(ReplaceStr(Str, '+', '%20'));
end;

The URIDecode routine was presented in my URL Decoding post.

URIDecodeQueryString has been added to UURIEncode.pas in my Delphi Doodlings repo. View the code.

No comments: