一、URL簡介
URL是網頁的地址,比如 http://www.cnblogs.com。Web 瀏覽器通過 URL 從 web 服務器請求頁面。
由於URL字符串常常會包含非ASCII字符,URL在傳輸過程中,往往出現錯誤。因此,可以將非字符串字符,讓一些特殊ASCII字符組合,代替非ASCII字符。這就是編碼轉換,當字符串傳輸后,可以返回原RUL字符串(解碼)。
URL只能使用 ASCII 字符集來通過因特網進行發送。URL編碼,就是會將RUL字符轉換為可通過因特網傳輸的格式。
URL編碼使用“%”其后跟隨兩位的十六進制數來替換非 ASCII 字符。比如“®”用“%A9”代替。
URL不能包含空格。URL編碼通常使用“+”來替換空格。
二、RUL編碼與解碼
1、uses HttpApp; //引用單元
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;