众所周知,旧版的Delphi里面,自带的http请求控件是indy的http,indy的控件请求https的时候,需要依赖于opensll,并且异步这块并不好.
新版的Delphi XE8以上的版本, 推出了TNetHttpClient,
TNetHttpClient既可以阻塞(如同INDY),又可以异步(这就很全面了)。
TNetHttpClient不再和INDY一样依赖OPENSSL。
先小小的尝试一下简单的post和get:
get:
function TForm3.http_get(sContentType, strData, url, self_head: string): string;
var
NetHTTPClient : TNetHTTPClient;
parametres : TStringStream;
begin
try
try
NetHTTPClient := TNetHTTPClient.Create(nil);
NetHTTPClient.ContentType :=sContentType;
NetHTTPClient.AcceptEncoding := 'UTF-8';
parametres := TStringStream.Create(strData, TEncoding.UTF8);
Result := NetHTTPClient.get(url, parametres).ContentAsString(TEncoding.UTF8);
finally
freeandnil(parametres);
freeandnil(NetHTTPClient);
end;
except
on e: Exception do
begin
// log('get_出现异常 :' + e.Message);
Result := e.Message;
end;
end;
end;
post:
function TForm3.http_post(sContentType, strData, url,
self_head: string): string;
var
NetHTTPClient : TNetHTTPClient;
parametres : TStringStream;
begin
try
try
NetHTTPClient := TNetHTTPClient.Create(nil);
NetHTTPClient.ContentType :=sContentType;
NetHTTPClient.AcceptEncoding := 'UTF-8';
parametres := TStringStream.Create(strData, TEncoding.UTF8);
Result := NetHTTPClient.Post(url, parametres).ContentAsString(TEncoding.UTF8);
finally
freeandnil(parametres);
freeandnil(NetHTTPClient);
end;
except
on e: Exception do
begin
// log('post_出现异常 :' + e.Message);
Result := e.Message;
end;
end;
end;
我们再来看下Delphi官方对应这块的定义:
System.Net.HttpClient.THTTPClient.Post
- Up to Parent: THTTPClient
Delphi
function Post(const AURL: string; const ASourceFile: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
function Post(const AURL: string; const ASource: TStrings; const AResponseContent: TStream = nil; const AEncoding: TEncoding = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
function Post(const AURL: string; const ASource: TStream; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
function Post(const AURL: string; const ASource: TMultipartFormData; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
C++
_di_IHTTPResponse __fastcall Post(const System::UnicodeString AURL, const System::UnicodeString ASourceFile, System::Classes::TStream* const AResponseContent = (System::Classes::TStream*)(0x0), const System::DynamicArray<System::Net::Urlclient::TNameValuePair> AHeaders = System::DynamicArray<System::Net::Urlclient::TNameValuePair>())/* overload */;
_di_IHTTPResponse __fastcall Post(const System::UnicodeString AURL, System::Classes::TStrings* const ASource, System::Classes::TStream* const AResponseContent = (System::Classes::TStream*)(0x0), System::Sysutils::TEncoding* const AEncoding = (System::Sysutils::TEncoding*)(0x0), const System::DynamicArray<System::Net::Urlclient::TNameValuePair> AHeaders = System::DynamicArray<System::Net::Urlclient::TNameValuePair>())/* overload */;
_di_IHTTPResponse __fastcall Post(const System::UnicodeString AURL, System::Classes::TStream* const ASource, System::Classes::TStream* const AResponseContent = (System::Classes::TStream*)(0x0), const System::DynamicArray<System::Net::Urlclient::TNameValuePair> AHeaders = System::DynamicArray<System::Net::Urlclient::TNameValuePair>())/* overload */;
_di_IHTTPResponse __fastcall Post(const System::UnicodeString AURL, System::Net::Mime::TMultipartFormData* const ASource, System::Classes::TStream* const AResponseContent = (System::Classes::TStream*)(0x0), const System::DynamicArray<System::Net::Urlclient::TNameValuePair> AHeaders = System::DynamicArray<System::Net::Urlclient::TNameValuePair>())/* overload */;
System.Net.HttpClient.THTTPClient.Get
- Up to Parent: THTTPClient
Delphi
function Get(const AURL: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse;
C++文章来源:https://www.toymoban.com/news/detail-738398.html
_di_IHTTPResponse __fastcall Get(const System::UnicodeString AURL, System::Classes::TStream* const AResponseContent = (System::Classes::TStream*)(0x0), const System::DynamicArray<System::Net::Urlclient::TNameValuePair> AHeaders = System::DynamicArray<System::Net::Urlclient::TNameValuePair>());
我们可以看到官方给与的这个新控件的定义及使用也很简单,下面我们自己创建个单元进行更深入的测试 文章来源地址https://www.toymoban.com/news/detail-738398.html
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Net.URLClient,
System.Net.HttpClient, System.Net.HttpClientComponent, Vcl.StdCtrls;
type
TForm1 = class(TForm)
NetHTTPClient1: TNetHTTPClient;
Button1: TButton;
Memo1: TMemo;
Button2: TButton;
NetHTTPClient2: TNetHTTPClient;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure NetHTTPClient1RequestCompleted(const Sender: TObject;
const AResponse: IHTTPResponse);
procedure Button2Click(Sender: TObject);
procedure NetHTTPClient2RequestCompleted(const Sender: TObject;
const AResponse: IHTTPResponse);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses System.NetEncoding;
{$R *.dfm}
function UrlDecode(const AStr: AnsiString): AnsiString;
var
Sp, Rp, Cp: PAnsiChar;
s: AnsiString;
begin
SetLength(Result, Length(AStr));
Sp := PAnsiChar(AStr);
Rp := PAnsiChar(Result);
Cp := Sp;
while Sp^ <> #0 do
begin
case Sp^ of
'+':
Rp^ := ' ';
'%':
begin
Inc(Sp);
if Sp^ = '%' then
Rp^ := '%'
else
begin
Cp := Sp;
Inc(Sp);
if (Cp^ <> #0) and (Sp^ <> #0) then
begin
s := AnsiChar('$') + Cp^ + Sp^;
Rp^ := AnsiChar(StrToInt(string(s)));
end;
end;
Cp := Cp;
end;
else
Rp^ := Sp^;
end;
Inc(Rp);
Inc(Sp);
end;
SetLength(Result, Rp - PAnsiChar(Result));
end;
procedure TForm1.Button1Click(Sender: TObject);
var
vHttp: TNetHTTPClient;
vUTF8, vGBK: TStringStream;
begin
vHttp := TNetHTTPClient.Create(nil);
vUTF8 := TStringStream.Create('', TEncoding.GetEncoding(65001));
vGBK := TStringStream.Create('', TEncoding.GetEncoding(936));
try
Memo1.Lines.Add('----------------阻塞----------------');
with vHttp do
begin
vUTF8.Clear;
ConnectionTimeout := 2000; // 2秒
ResponseTimeout := 10000; // 10秒
AcceptCharSet := 'utf-8';
AcceptEncoding := '65001';
AcceptLanguage := 'zh-CN';
ContentType := 'text/html';
UserAgent := 'Embarcadero URI Client/1.0';
try
Get('http://offeu.com/utf8.txt', vUTF8);
Memo1.Lines.Add('utf8:' + TNetEncoding.URL.UrlDecode(vUTF8.DataString));
except
on E: Exception do
// Error sending data: (12002) 操作超时.
// Error receiving data: (12002) 操作超时
if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error sending data'
then
Memo1.Lines.Add('utf8:连接失败!')
else if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error receiving data'
then
Memo1.Lines.Add('utf8:接收失败,请延长接收超时时间!')
else
Memo1.Lines.Add('utf8:' + E.Message);
end;
vGBK.Clear;
AcceptCharSet := 'gbk';
AcceptEncoding := '936';
AcceptLanguage := 'zh-CN';
ContentType := 'text/html';
UserAgent := 'Embarcadero URI Client/1.0';
Get('http://offeu.com/gbk.txt', vGBK);
Memo1.Lines.Add('gbk:' + string(UrlDecode(AnsiString(vGBK.DataString))));
end;
Memo1.Lines.Add('----------------异步----------------');
with NetHTTPClient1 do
begin
Asynchronous := true;
ConnectionTimeout := 10000; // 10秒
ResponseTimeout := 10000; // 10秒
AcceptCharSet := 'utf-8';
AcceptEncoding := '65001';
AcceptLanguage := 'zh-CN';
ContentType := 'text/html';
UserAgent := 'Embarcadero URI Client/1.0';
Get('http://offeu.com/utf8.txt');
end;
finally
vUTF8.Free;
vGBK.Free;
vHttp.Free;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
vHttp: TNetHTTPClient;
vS: TStringStream;
begin
// 这里用的 APPCODE 是阿里云市场中的api,需要申请。
vHttp := TNetHTTPClient.Create(nil);
vS := TStringStream.Create('', TEncoding.GetEncoding(65001));
try
with vHttp do
begin
Memo1.Lines.Add('--------------SSL阻塞--------------');
vS.Clear;
ConnectionTimeout := 10000; // 10秒
ResponseTimeout := 10000; // 10秒
CustomHeaders['Authorization'] :=
'APPCODE 你申请的appcode';
Accept := 'application/json;';
ContentType := 'application/json; charset=utf-8;';
UserAgent := 'Embarcadero URI Client/1.0';
Get('https://dm-81.data.aliyun.com/rest/160601/ip/getIpInfo.json?'
+ 'ip=60.191.244.5', vS);
Memo1.Lines.Add('ssl:'
+ string(TNetEncoding.URL.UrlDecode(vS.DataString)));
end;
finally
vS.Free;
vHttp.Free;
end;
Memo1.Lines.Add('--------------SSL异步--------------');
with NetHTTPClient2 do
begin
Asynchronous := true;
ConnectionTimeout := 10000; // 10秒
ResponseTimeout := 10000; // 10秒
CustomHeaders['Authorization'] :=
'APPCODE 你申请的appcode';
Accept := 'application/json;';
ContentType := 'application/json; charset=utf-8;';
UserAgent := 'Embarcadero URI Client/1.0';
Get('https://dm-81.data.aliyun.com/rest/160601/ip/getIpInfo.json?'
+ 'ip=60.191.244.5');
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
vHttp: TNetHTTPClient;
vS: TStringStream;
vList: TStrings;
begin
vHttp := TNetHTTPClient.Create(nil);
vList := TStringList.Create;
vS := TStringStream.Create;
try
Memo1.Lines.Add('----------------Post阻塞----------------');
vS.Clear;
with vHttp do
begin
ConnectionTimeout := 2000; // 2秒
ResponseTimeout := 10000; // 10秒
AcceptCharSet := 'utf-8';
AcceptEncoding := '65001';
AcceptLanguage := 'zh-CN';
ContentType := 'text/html';
UserAgent := 'Embarcadero URI Client/1.0';
vList.Clear;
vList.Values['id'] := 'test';
vList.Values['pwd'] := 'test';
vList.Values['cmd'] := '1';
try
Post('http://60.191.220.219:8090', vList, vS); // utf8进gbk出
// Memo1.Lines.Add('post:' + TNetEncoding.URL.UrlDecode(vS.DataString));
Memo1.Lines.Add('post:' + vS.DataString);
except
on E: Exception do
// Error sending data: (12002) 操作超时.
// Error receiving data: (12002) 操作超时
if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error sending data'
then
Memo1.Lines.Add('post:连接失败!')
else if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error receiving data'
then
Memo1.Lines.Add('post:接收失败,请延长接收超时时间!')
else
Memo1.Lines.Add('post:' + E.Message);
end;
end;
finally
vS.Free;
vList.Free;
vHttp.Free;
end;
end;
procedure TForm1.NetHTTPClient1RequestCompleted(const Sender: TObject;
const AResponse: IHTTPResponse);
begin
Memo1.Lines.Add('utf8:' + TNetEncoding.URL.UrlDecode(
AResponse.ContentAsString(TEncoding.GetEncoding(65001))));
end;
procedure TForm1.NetHTTPClient2RequestCompleted(const Sender: TObject;
const AResponse: IHTTPResponse);
begin
Memo1.Lines.Add('ssl:' + TNetEncoding.URL.UrlDecode(
AResponse.ContentAsString(TEncoding.GetEncoding(65001))));
end;
end.
到了这里,关于Delphi XE新的http控件TNetHTTPClient的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!