Delphi下URL汉字编码解码的两个函数

时间:2022-01-19 13:14:08

//汉字URL编码函数
function URLEncode(const S: string; const InQueryString: Boolean): string;
var
  Idx: Integer; //逐个字符循环直至字符串结束
begin
  Result := '';
  for Idx := 1 to Length(S) do
  begin
    case S[Idx] of
      'A'..'Z', 'a'..'z', '0'..'9', '-', '_', '.':
        Result := Result + S[Idx];
      ' ':
        if InQueryString then
          Result := Result + '+'
        else
          Result := Result + '%20';
      else
        Result := Result + '%' + SysUtils.IntToHex(Ord(S[Idx]), 2);
    end;
  end;
end;

//汉字URL解码函数
function URLDecode(const S: string): string;
var
  Idx: Integer;  //逐个字符循环直至字符串结束
  Hex: string;   //十六进制字符串
  Code: Integer;  //十六进制字符(-1表示错误)
begin
  //初始化解码结果和字符串索引
  Result := '';
  Idx := 1;
  //逐个字符循环解码
  while Idx <= Length(S) do
  begin
    case S[Idx] of
      '%':
      begin
        //%后面应跟两个Hex字符,否则抛出异常
        if Idx <= Length(S) - 2 then
        begin
          //必须有足够的位数,解码十六进制数据
          Hex := S[Idx+1] + S[Idx+2];
          Code := SysUtils.StrToIntDef('$' + Hex, -1);
          Inc(Idx, 2);
        end
        else
          //位数不足,出错
          Code := -1;
        //检查异常,如果检查到就抛出异常
        if Code = -1 then
          raise SysUtils.EConvertError.Create(
            'Invalid hex digit in URL'
          );
        //解码成功,并将字符加到Result里
        Result := Result + Chr(Code);
      end;
      '+':
        //+将解码为空格
        Result := Result + ' '
      else
        //其他字符不用解码
        Result := Result + S[Idx];
    end;
    Inc(Idx);
  end;
end;

Delphi下URL汉字编码解码的两个函数
使用实例:

procedure TForm1.Button1Click(Sender: TObject);
begin
  Edit2.Text := URLEncode(edit1.Text,false);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  Edit1.Text := URLDecode(Edit2.Text);
end;

http://www.lsworks.net/article/40.html