在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Delphi UTF/URL编码/解码 UTF8Encode、UTF8Decode、URLEncode、URLDecode 一、URL简介
二、URL编码与解码 2、编码,先UTF8编码,然后再URL编码,不然和标准的url_encode()编码结果不一致,查询结果自然不是预期的 S2 := HttpEncode(UTF8Encode(S1)); 3、解码,先URL解码,然后再UTF8解码,否则结果是乱码。 S1 := UTF8Decode(HttpDecode(S2)); 以上是内置函数调用 三、URLEncode、URLDecode //URLEncode
function URLDecode(const S: string): string;
var
Idx: Integer; // loops thru chars in string
Hex: string; // string of hex characters
Code: Integer; // hex character code (-1 on error)
begin
// Intialise result and string index
Result := '';
Idx := 1;
// Loop thru string decoding each character
while Idx <= Length(S) do
begin
case S[Idx] of
'%':
begin
// % should be followed by two hex digits - exception otherwise
if Idx <= Length(S) - 2 then
begin
// there are sufficient digits - try to decode hex digits
Hex := S[Idx+1] + S[Idx+2];
Code := SysUtils.StrToIntDef('$' + Hex, -1);
Inc(Idx, 2);
end
else
// insufficient digits - error
Code := -1;
// check for error and raise exception if found
if Code = -1 then
raise SysUtils.EConvertError.Create(
'Invalid hex digit in URL'
);
// decoded OK - add character to result
Result := Result + Chr(Code);
end;
'+':
// + is decoded as a space
Result := Result + ' '
else
// All other characters pass thru unchanged
Result := Result + S[Idx];
end;
Inc(Idx);
end;
end;
//URLDecode
function URLEncode(const S: string; const InQueryString: Boolean): string;
var
Idx: Integer; // loops thru characters in string
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;
四、示例 示例1: uses Httpapp; begin sStr:=HttpEncode(UTF8EnCode('滔Roy')); //或: //sStr:=HttpEncode(AnsiToUtf8('滔Roy')); end; 示例2: uses IdURI; begin sStr := TIdURI.URLEncode(str); // sStr := TIdURI.URLDecode(str); end;
创建时间:2019.12.03 更新时间:2021.04.29 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论