市面上的URLDecode编码函数,只能支持%xx%xx的格式,如果使用JS的escape函数编码中文的字符串,则会导致解码不正确!
下面是Kingron改进的URLDecode函数:
function URLDecode(psSrc: string): string;
var
i: Integer;
ESC: string[2];
CharCode: integer;
WESC: string[4];
begin
Result := '';
psSrc := StringReplace(psSrc, '+', ' ', [rfReplaceAll]);
i := 1;
while i <= Length(psSrc) do
begin
if psSrc[i] <> '%' then
begin
Result := Result + psSrc[i]
end
else
begin
Inc(i);
if (psSrc[i] = 'u') and (i > 1) and (psSrc[i - 1]= '%') then
begin
Inc(i);
WESC := Copy(psSrc, i, 4);
try
CharCode := StrToInt('$' + WESC);
if (CharCode > 0) and (CharCode < 65536) then
Result := Result + WideChar(CharCode);
except
end;
Inc(i, 3);
end
else
begin
ESC := Copy(psSrc, i, 2);
Inc(i, 1);
try
CharCode := StrToInt('$' + ESC);
if (CharCode > 0) and (CharCode < 256) then
Result := Result + Char(CharCode);
except
end;
end;
end;
Inc(i);
end;
end;