URLEncode и URLDecode
сентября 19, 2009
При написании программ, взаимодействующих по сети, иногда встает проблема передачи, приема и распознавания символов локального алфавита. Например, при написании клиента для некоего сайта. Мы, собственно, наталкиваемся на отсутствие в Delphi функций URLEncode и URLDecode. Поэтому приходится их писать самим. Ниже приведены упомянутые функции. Чтобы лишний раз не изобретать велосипед.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | function DigitToHex(Digit: Integer): Char; begin case Digit of 0..9: Result := Chr(Digit + Ord('0')); 10..15: Result := Chr(Digit - 10 + Ord('A')); else Result := '0'; end; end; // DigitToHex function URLEncode(const S: string): string; var i, idx, len: Integer; begin len := 0; for i := 1 to Length(S) do if ((S[i] >= '0') and (S[i] < = '9')) or ((S[i] >= 'A') and (S[i] < = 'Z')) or ((S[i] >= 'a') and (S[i] < = 'z')) or (S[i] = ' ') or (S[i] = '_') or (S[i] = '*') or (S[i] = '-') or (S[i] = '.') then len := len + 1 else len := len + 3; SetLength(Result, len); idx := 1; for i := 1 to Length(S) do if S[i] = ' ' then begin Result[idx] := '+'; idx := idx + 1; end else if ((S[i] >= '0') and (S[i] < = '9')) or ((S[i] >= 'A') and (S[i] < = 'Z')) or ((S[i] >= 'a') and (S[i] < = 'z')) or (S[i] = '_') or (S[i] = '*') or (S[i] = '-') or (S[i] = '.') then begin Result[idx] := S[i]; idx := idx + 1; end else begin Result[idx] := '%'; Result[idx + 1] := DigitToHex(Ord(S[i]) div 16); Result[idx + 2] := DigitToHex(Ord(S[i]) mod 16); idx := idx + 3; end; end; // URLEncode function URLDecode(const S: string): string; var i, idx, len, n_coded: Integer; function WebHexToInt(HexChar: Char): Integer; begin if HexChar < '0' then Result := Ord(HexChar) + 256 - Ord('0') else if HexChar <= Chr(Ord('A') - 1) then Result := Ord(HexChar) - Ord('0') else if HexChar <= Chr(Ord('a') - 1) then Result := Ord(HexChar) - Ord('A') + 10 else Result := Ord(HexChar) - Ord('a') + 10; end; begin len := 0; n_coded := 0; for i := 1 to Length(S) do if n_coded >= 1 then begin n_coded := n_coded + 1; if n_coded >= 3 then n_coded := 0; end else begin len := len + 1; if S[i] = '%' then n_coded := 1; end; SetLength(Result, len); idx := 0; n_coded := 0; for i := 1 to Length(S) do if n_coded >= 1 then begin n_coded := n_coded + 1; if n_coded >= 3 then begin Result[idx] := Chr((WebHexToInt(S[i - 1]) * 16 + WebHexToInt(S[i])) mod 256); n_coded := 0; end; end else begin idx := idx + 1; if S[i] = '%' then n_coded := 1; if S[i] = '+' then Result[idx] := ' ' else Result[idx] := S[i]; end; end; // URLDecode |
Оставить комментарий
Вы должны быть зарегистрированы чтобы оставить комментарий.