Two functions of Delphi URL Chinese character coding decoding

Source: Internet
Author: User
Tags urlencode

Chinese Character URL coding function
function UrlEncode (const s:string; const Inquerystring:boolean): string;
Var
Idx:integer; Cycle through characters until the end of the 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

Chinese character URL decoding function
function UrlDecode (const s:string): string;
Var
Idx:integer; Cycle through characters until the end of the string
hex:string; hexadecimal string
Code:integer; hexadecimal character (-1 = error)
Begin
Initial dissolve code result and string index
Result: = ';
IDX: = 1;
Loop-by-character decoding
While Idx <= Length (S) do
Begin
Case S[IDX] of
‘%‘:
Begin
% should be followed by two hex characters, otherwise throw an exception
If Idx <= Length (S)-2 Then
Begin
Must have enough digits to decode the hexadecimal data
Hex: = s[idx+1] + s[idx+2];
Code: = Sysutils.strtointdef (' $ ' + Hex,-1);
INC (IDX, 2);
End
Else
Insufficient number of bits, error
Code: =-1;
Check for exceptions, throw exceptions if checked
If Code =-1 Then
Raise SysUtils.EConvertError.Create (
' Invalid hex digit in URL '
);
Decoding succeeds and multibyte the word into result
Result: = result + CHR (Code);
End
' + ':
+ will decode to a space
Result: = result + '
Else
No other characters to decode
Result: = result + S[IDX];
End
INC (IDX);
End
End


Usage examples:

Procedure Tform1.button1click (Sender:tobject);
Begin
Edit2.text: = UrlEncode (edit1. Text,false);
End

Procedure Tform1.button2click (Sender:tobject);
Begin
Edit1.text: = UrlDecode (Edit2.text);
End

Http://www.lsworks.net/article/40.html

Two functions of Delphi URL Chinese character coding decoding

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.