url 中文编解码

unit Unit1;

interface

uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IdBaseComponent,
IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, Web.HTTPApp;

type
TForm1 = class(TForm)
http: TIdHTTP;
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

// 中文转换为javascript字串
function EncodeJSStr(const value: Widestring): Widestring;
var
P: PWideChar;
begin
Result := '';
P := PWideChar(value);
while P^ <> #0 do
begin
case P^ of
'"', '\', '/':
Result := Result + '\' + P^;
#$08:
Result := Result + '\b';
#$0C:
Result := Result + '\f';
#$0A:
Result := Result + '\n';
#$0D:
Result := Result + '\r';
#$09:
Result := Result + '\t';
else
if WORD(P^) > $FF then
Result := Result + LowerCase(Format('\u%x', [WORD(P^)]))
else
Result := Result + P^;
end;
inc(P);
end;
end;

// javascript字串还原为汉字
function DecodeJSStr(const value: Widestring): Widestring;
var
P: PWideChar;
v: WideChar;
tmp: Widestring;
begin
Result := '';
P := PWideChar(value);
while P^ <> #0 do
begin
v := #0;
case P^ of
'\':
begin
inc(P);
case P^ of
'"', '\', '/':
v := P^;
'b':
v := #$08;
'f':
v := #$0C;
'n':
v := #$0A;
'r':
v := #$0D;
't':
v := #$09;
'u':
begin
tmp := Copy(P, 2, 4);
v := WideChar(StrToInt('$' + tmp));
inc(P, 4);
end;
end;
end;
else
v := P^;
end;
Result := Result + v;
inc(P);
end;
end;

function urlEncode(str: string): string;
var
b: Byte;
begin
for b in BytesOf(UTF8Encode(str)) do
Result := Format('%s%%%.2x', [Result, b]);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
S, r: string;
begin
// S := urlEncode('咏南工作室');
// s:= HttpEncode(AnsiToUtf8('咏南工作室'));
s:=HTTPEncode(UTF8Encode('咏南工作室'));
r := http.get('http://localhost:8080/yn/rest/TServerMethods1/echo/' + S);
// Memo1.Text:= HTTPDecode(r);
Memo1.Text := DecodeJSStr(r);
end;

end.

posted @ 2014-07-02 10:38  delphi中间件  阅读(2589)  评论(0编辑  收藏  举报