TNetHttpClient的用法

TNetHttpClient是DELPHI XE8新增加的控件。

在之前,我们一般都是使用IDHTTP控件,但在安卓、IOS等非WINDOWS平台,IDHTTP访问HTTPS却不行了。

大家知道INDY的SSL访问局限于WINDOWS平台,并不支持跨平台HTTPS访问。

鉴于以上原因,所以EMB才推出了TNetHttpClient。

TNetHttpClient既可以阻塞(如同INDY),又可以异步(这就很全面了)。

TNetHttpClient不再和INDY一样依赖OPENSSL。

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.

  

TNetHttpClient的用法的更多相关文章

  1. EditText 基本用法

    title: EditText 基本用法 tags: EditText,编辑框,输入框 --- EditText介绍: EditText 在开发中也是经常用到的控件,也是一个比较必要的组件,可以说它是 ...

  2. jquery插件的用法之cookie 插件

    一.使用cookie 插件 插件官方网站下载地址:http://plugins.jquery.com/cookie/ cookie 插件的用法比较简单,直接粘贴下面代码示例: //生成一个cookie ...

  3. Java中的Socket的用法

                                   Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...

  4. [转载]C#中MessageBox.Show用法以及VB.NET中MsgBox用法

    一.C#中MessageBox.Show用法 MessageBox.Show (String) 显示具有指定文本的消息框. 由 .NET Compact Framework 支持. MessageBo ...

  5. python enumerate 用法

    A new built-in function, enumerate() , will make certain loops a bit clearer. enumerate(thing) , whe ...

  6. [转载]Jquery中$.get(),$.post(),$.ajax(),$.getJSON()的用法总结

    本文对Jquery中$.get(),$.post(),$.ajax(),$.getJSON()的用法进行了详细的总结,需要的朋友可以参考下,希望对大家有所帮助. 详细解读Jquery各Ajax函数: ...

  7. 【JavaScript】innerHTML、innerText和outerHTML的用法区别

    用法: <div id="test">   <span style="color:red">test1</span> tes ...

  8. chattr用法

    [root@localhost tmp]# umask 0022 一.chattr用法 1.创建空文件attrtest,然后删除,提示无法删除,因为有隐藏文件 [root@localhost tmp] ...

  9. 萌新笔记——vim命令“=”、“d”、“y”的用法(结合光标移动命令,一些场合会非常方便)

    vim有许多命令,网上搜有一堆贴子.文章列举出各种功能的命令. 对于"="."d"."y",我在无意中发现了它们所具有的相同的一些用法,先举 ...

随机推荐

  1. Python使用selenium模拟点击(二)

    本篇文章是接着第一篇文章讲的 具体可看第一篇:https://www.cnblogs.com/whatarey/p/10477754.html 要实现功能>搜索完毕,自动点击 这个功能做的停操蛋 ...

  2. 使用pyinstaller打包使用cx_Oracle模块的程序出现The specified module could not be found的问题

    pyinstaller看起来并不会将动态链接库自动打包,所以我们需要告诉pyinstaller要打包哪些动态链接库,步骤如下(假设python文件名为 oracletest.py): 1. 使用pyi ...

  3. zencart用sql语句设置默认语言

    有时候拷贝站的时候,由于语言文件的缺失,导致页面空白,需要将默认语言更改为英语,以下sql语句可以一定搞定: UPDATE `configuration` SET `configuration_val ...

  4. 大数据之路week05--day01(I/O流阶段一 之File)

    众所周知,我们电脑中有许许多多的文件夹和文件,文件的形式也有许多不同的格式,文件夹中也可以新建文件夹的存在,也就是多层的一步一步的嵌套. 我们想要实现I/O操作,就必须知道硬盘上文件的表现形式. 而J ...

  5. 使用 webpack-bundle-analyzer 分析 webpack 代码库拆分块

    github:https://github.com/webpack-contrib/webpack-bundle-analyzer 1.安装: cnpm install webpack-bundle- ...

  6. idea java快速生成返回值

    ctrl+alt+V 或者

  7. SqlHelper发布—比Pagehelper更好用的分页插件

    SqlHelper发布-比PageHelper性能更高 起源 前段时间开启了一个新的项目,在选择分页插件时,发现github上很流行的一个是pagehelper,在百度上搜索了一下,使用量.由于项目紧 ...

  8. [ES2019] Represent Collision-free String Constants as Symbols in JavaScript

    ES2019 introduces the Symbol.prototype.description property. In this lesson, we'll learn why this pr ...

  9. PHP mysqli_connect() 函数

    打开一个到 MySQL 服务器的新的连接: mysqli_connect(host,username,password,dbname,port,socket); <?php $con=mysql ...

  10. scrapy 学习笔记2 数据持久化

    前情提要:校花网爬取,并进行数据持久化 数据持久化操作 --编码流程: 1:数据解析 2:封装item 类 3: 将解析的数据存储到实例化好的item 对象中 4:提交item 5:管道接收item然 ...