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


    //汉字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;


    使用实例:

    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

  • 相关阅读:
    一种C#读写二进制文件的通用方法
    关于POP3协议的一点资料
    关于看图工具的几点想法
    在WPF程序中将控件所呈现的内容保存成图像
    Nuget挂了的解决方法
    VisualStudio 2012中的单元测试
    在Andorid平板上体验Windows8的猜想
    创建自己的awaitable类型
    【转载】:最佳注释
    百度云盘试用
  • 原文地址:https://www.cnblogs.com/findumars/p/4999014.html
Copyright © 2020-2023  润新知