PDA

Ver la Versión Completa : URL Encode / Decode


seoane
11-06-2006, 03:21:55
Esta funcion devuelve una cadena en donde todos los caracteres no-alfanuméricos, excepto -_., son reemplazados con un signo de porcentaje (%) seguido de dos dígitos hexadecimales. Este es el tipo de codificación descrito en el RFC 1738.


function URLEncode(Str: string): string;
var
i: integer;
begin
Result:= '';
for i:= 1 to Length(Str) do
if Str[i] in ['A'..'Z','a'..'z','0'..'9','-','_','.'] then
Result:= Result + Str[ i ]
else
Result:= Result + '%' + IntToHex(Ord(Str[ i ]),2);
end;


Esta otra funcion hace el proceso inverso

function URLDecode(Str: string): string;
var
i: integer;
begin
Result:= '';
while Length(Str) > 0 do
begin
if Copy(Str, 1, 1) = '%' then
begin
if not TryStrToInt('$' + Copy(Str, 2, 2),i) then
begin
Result:= '';
Exit;
end;
Result:= Result + Char(i);
Delete(Str, 1, 2);
end else Result:= Result + Copy(Str, 1, 1);
Delete(Str,1,1);
end;
end;


Por razones historicas a veces se sigue utilizando el caractrer '+' para sustituir los espacio en blanco en ves de utilizar '%20' como dice el estandar. Si queremos seguir usando esta forma utilizaremos algo como esto:


function URLEncode(Str: string): string;
var
i: integer;
begin
Result:= '';
for i:= 1 to Length(Str) do
if Str[ i ] in ['A'..'Z','a'..'z','0'..'9','-','_','.'] then
Result:= Result + Str[i]
else if Str[ i ] = ' ' then
Result:= Result + '+'
else
Result:= Result + '%' + IntToHex(Ord(Str[ i ]),2);
end;

function URLDecode(Str: string): string;
var
i: integer;
begin
Result:= '';
Str:= StringReplace(Str, '+', ' ', [rfReplaceAll]);
while Length(Str) > 0 do
begin
if Copy(Str, 1, 1) = '%' then
begin
if not TryStrToInt('$' + Copy(Str, 2, 2),i) then
begin
Result:= '';
Exit;
end;
Result:= Result + Char(i);
Delete(Str, 1, 2);
end else Result:= Result + Copy(Str, 1, 1);
Delete(Str,1,1);
end;
end;


Ejemplo de uso:

var
s: string;
begin
s:= URLEncode('Hola @mumundo.###*');
ShowMessage(s);
ShowMessage(URLDecode(s));
end;