Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Trucos (https://www.clubdelphi.com/foros/forumdisplay.php?f=52)
-   -   URL Encode / Decode (https://www.clubdelphi.com/foros/showthread.php?t=80460)

seoane 11-06-2006 02:21:55

URL Encode / Decode
 
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.

Código Delphi [-]
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
Código Delphi [-]
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:

Código Delphi [-]
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:
Código Delphi [-]
var
  s: string;
begin
  s:= URLEncode('Hola @mumundo.###*');
  ShowMessage(s);
  ShowMessage(URLDecode(s));
end;


La franja horaria es GMT +2. Ahora son las 06:07:28.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi