以下是Delphi中的urlencode和urldecode函数,使用时注意一下delphi的高版本和低版本的区别,在新版delphi中,已改用unicode,所以要区分好PChar、PAnsiChar和PWideChar。

function UrlDecode(const AStr: AnsiString): AnsiString;

var

   Sp, Rp, Cp: PAnsiChar;

   s: AnsiString;

begin

   SetLength(Result, Length(AStr));

   Sp := PAnsiChar(AStr);

   Rp := PAnsiChar(Result);

   Cp := Sp;

   while Sp^ <> #0 do

   begin
      case Sp^ of

         '+':

            Rp^ := ' ';

         '%':

            begin

               // Look for an escaped % (%%) or %<hex> encoded character

               Inc(Sp);

               if Sp^ = '%' then

                  Rp^ := '%'

               else

               begin

                  Cp := Sp;

                  Inc(Sp);

                  if (Cp^ <> #0) and (Sp^ <> #0) then

                  begin

                     s := AnsiChar('$') + Cp^ + Sp^;

                     Rp^ := AnsiChar(StrToInt(string(s)));

                  end;

               end;

            end;

         else

            Rp^ := Sp^;

         end;

         Inc(Rp);

         Inc(Sp)

      end;

   SetLength(Result, Rp - PAnsiChar(Result));

end;

function UrlEncode(const AStr: AnsiString): AnsiString;

const

  NoConversion = ['A' .. 'Z', 'a' .. 'z', '*', '@', '.', '_', '-','0' .. '9', '$', '!', '''', '(', ')'];

var

   Sp, Rp: PAnsiChar;

begin

   SetLength(Result, Length(AStr) * 3);

   Sp := PAnsiChar(AStr);

   Rp := PAnsiChar(Result);

   while Sp^ <> #0 do

   begin

      if Sp^ in NoConversion then

         Rp^ := Sp^

      else

         if Sp^ = ' ' then

            Rp^ := '+'

         else

         begin

            FormatBuf(Rp^, 3, AnsiString('%%%.2x'), 6, [Ord(Sp^)]);

            Inc(Rp, 2);

         end;

      Inc(Rp);

      Inc(Sp);

   end;

   SetLength(Result, Rp - PAnsiChar(Result));

end;