首页 > 解决方案 > 我在使用 urldecode 方法时遇到错误

问题描述

使用该方法解码 url 编码的字符时出现以下错误TNetEncoding.URL.Decode()

目标多字节代码页中不存在 Unicode 字符的映射

url参数是

?call=ExportEventPerspectiveAsCSV&min=2020-03-09%2000:00:00&max=2020-03-09%2023:59:59&type=csv&folder=%F6%E7

我的代码:

var
  Str: TStringList;
begin
  Str:= TStringList.Create();
  Str.Text := TNetEncoding.URL.Decode(ARequestInfo.QueryParams);// URLDecode(Str.Text);
  Str.Text := StringReplace(Str.Text, '&', #13, [rfReplaceAll]);
end;

标签: delphiurldecode

解决方案


默认情况下,TNetEncoding.URL将编码的字节序列解码为 UTF-8,但%F6%E7不代表有效的 UTF-8 字节序列,因此无法将其解码为 UTF-8,因此出现“无映射”错误。

AEncoding您需要在 的可选参数中指定正确的字符集编码(在这种情况下您必须弄清楚它的含义)TURLEncoding.Decode(),例如:

var
  Str: TStringList;
  Enc: TEncoding;
begin
  Str := TStringList.Create;
  try
    Enc := TEncoding.GetEncoding('TheCharsetHere'); // <-- !!!
    try
      Str.Text := TNetEncoding.URL.Decode(ARequestInfo.QueryParams, [TDecodeOption.PlusAsSpaces], Enc);
    finally
      Enc.Free;
    end;
    Str.Text := StringReplace(Str.Text, '&', #13, [rfReplaceAll]);
  finally
    Str.Free;
  end;
end;

也就是说,您确实需要在解码之前拆分值对,而不是在解码拆分它们。这样,&编码为的字符%26不会受到虐待,例如:

var
  Str: TStringList;
  Enc: TEncoding;
  I: Integer;
begin
  Str := TStringList.Create;
  try
    Enc := TEncoding.GetEncoding('TheCharsetHere'); // <-- !!!
    try
      Str.Delimiter := '&';
      Str.StrictDelimiter := True;
      Str.DelimitedText := ARequestInfo.QueryParams;
      for I := 0 to Str.Count-1 do begin
        Str[I] := TNetEncoding.URL.Decode(Str[I], [TDecodeOption.PlusAsSpaces], Enc);
      end;
    finally
      Enc.Free;
    end;
  finally
    Str.Free;
  end;
end;

推荐阅读