本文整理自网络,侵删。
utf-8编码
unit Unit1;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdCookieManager,types, StdCtrls,httpapp;type TForm1 = class(TForm) IdHTTP1: TIdHTTP; …… …… private { Private declarations } public { Public declarations } end;var Form1: TForm1; t:string;implementation{$R *.dfm} procedure TForm1.Toupiao(); var Params1:TStrings; ChangeStr,yyy, url:string; tmp:string; begin yyy:='测试'; <span style="color: #FF0000;">ChangeStr:=UTF8Encode(yyy);</span> IdHTTP1.AllowCookies:=false; Params1 :=TStringList.Create; try IdHTTP1.Request.Accept:= '*/*'; //IdHTTP1.Request.X-flash-version := 10,0,32,18 IdHTTP1.Request.ContentType:= 'application/x-www-form-urlencoded'; IdHTTP1.Request.Host:= www.xxx.com'; IdHTTP1.Request.AcceptEncoding:= 'gzip, deflate'; IdHTTP1.Request.Referer:= 'http://www.xxx.com/index.php'; IdHTTP1.Request.CustomHeaders.Clear; IdHTTP1.Request.CustomHeaders.add(t); try Params1.Append('id=602'); Params1.Append('name='+ChangeStr); try url := 'http://www.xxx.com/index.php'; IdHTTP1.HandleRedirects:=true; tmp:=idhttp1.Post(url,Params1); except end; except end; finally Params1.Free; end;end;
关键句 ChangeStr:=UTF8Encode(yyy);
GB2312编码
type
ISO8859String = type AnsiString(1252);
GB2312String = type AnsiString(936);
function URIParamsEncode(const ASrc: RawByteString): RawByteString;
const
UnsafeChars = ['*', '#', '%', '<', '>', '[', ']'];
ASCIIChars = [#$21..#$7f];
AnsiHex : array[0..15]of AnsiChar = '0123456789ABCDEF';
var
i, len : Integer;
b : Byte;
c : AnsiChar;
sBuff : RawByteString;
pSrc, pDst : PAnsiChar;
begin
len := Length(ASrc);
if(ASrc[len]='&')then Dec(len);
SetLength(sBuff, len*3);
pSrc := Pointer(ASrc);
pDst := Pointer(sBuff);
for i := 0 to Len - 1 do
begin
c := pSrc[i];
if((c in UnsafeChars)or(not(c in ASCIIChars)))then
begin
b := Byte(c);
pDst[0] := '%';
pDst[1] := AnsiHex[b shr 4];
pDst[2] := AnsiHex[b and $f];
Inc(pDst, 3);
end else
begin
pDst^ := c;
Inc(pDst);
end;
end;
pSrc := Pointer(sBuff);
SetString(Result, pSrc, pDst-pSrc);
end;
var
lstPost : TStringList;
stmTmp : TMemoryStream;
sI8859 : ISO8859String;
sGb2312 : GB2312String;
begin
lstPost := TStringList.Create;
stmTmp := TMemoryStream.Create;
try
lstPost.Add('mobile='+Edit1.Text);
lstPost.Add('action=mobile');
lstPost.Add('test=测 试');
IdHTTP1.Request.ContentType := 'application/x-www-form-urlencoded';
sGb2312 := URIParamsEncode( GB2312String(StringReplace(
lstPost.Text, #13#10, '&', [rfReplaceAll] )) );
stmTmp.Write(sGb2312[1], Length(sGb2312));
stmTmp.Position := 0;
sI8859 := ISO8859String(IdHTTP1.Post(URLPost, stmTmp));
SetString(sGb2312, PAnsiChar(sI8859), Length(sI8859));
Memo1.Text := string(sGB2312);
finally
stmTmp.Free;
lstPost.Free;
end;
相关阅读 >>
Delphi firedac 的recordcount 相关测试 记录
Delphi 将自己的app.ico应用程序图表添加到dephi资源文件res中
Delphi rest 服务器返回utf16编码转换成正常string
更多相关阅读请进入《Delphi》频道 >>