当前位置:   article > 正文

Delphi XE新的http控件TNetHTTPClient_delphi urldecode

delphi urldecode

        众所周知,旧版的Delphi里面,自带的http请求控件是indy的http,indy的控件请求https的时候,需要依赖于opensll,并且异步这块并不好.

        新版的Delphi XE8以上的版本, 推出了TNetHttpClient,

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

        TNetHttpClient不再和INDY一样依赖OPENSSL

先小小的尝试一下简单的post和get:

get:

  1. function TForm3.http_get(sContentType, strData, url, self_head: string): string;
  2. var
  3. NetHTTPClient : TNetHTTPClient;
  4. parametres : TStringStream;
  5. begin
  6. try
  7. try
  8. NetHTTPClient := TNetHTTPClient.Create(nil);
  9. NetHTTPClient.ContentType :=sContentType;
  10. NetHTTPClient.AcceptEncoding := 'UTF-8';
  11. parametres := TStringStream.Create(strData, TEncoding.UTF8);
  12. Result := NetHTTPClient.get(url, parametres).ContentAsString(TEncoding.UTF8);
  13. finally
  14. freeandnil(parametres);
  15. freeandnil(NetHTTPClient);
  16. end;
  17. except
  18. on e: Exception do
  19. begin
  20. // log('get_出现异常 :' + e.Message);
  21. Result := e.Message;
  22. end;
  23. end;
  24. end;

post:

  1. function TForm3.http_post(sContentType, strData, url,
  2. self_head: string): string;
  3. var
  4. NetHTTPClient : TNetHTTPClient;
  5. parametres : TStringStream;
  6. begin
  7. try
  8. try
  9. NetHTTPClient := TNetHTTPClient.Create(nil);
  10. NetHTTPClient.ContentType :=sContentType;
  11. NetHTTPClient.AcceptEncoding := 'UTF-8';
  12. parametres := TStringStream.Create(strData, TEncoding.UTF8);
  13. Result := NetHTTPClient.Post(url, parametres).ContentAsString(TEncoding.UTF8);
  14. finally
  15. freeandnil(parametres);
  16. freeandnil(NetHTTPClient);
  17. end;
  18. except
  19. on e: Exception do
  20. begin
  21. // log('post_出现异常 :' + e.Message);
  22. Result := e.Message;
  23. end;
  24. end;
  25. end;

我们再来看下Delphi官方对应这块的定义:

System.Net.HttpClient.THTTPClient.Post

Delphi

  1. function Post(const AURL: string; const ASourceFile: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
  2. function Post(const AURL: string; const ASource: TStrings; const AResponseContent: TStream = nil; const AEncoding: TEncoding = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
  3. function Post(const AURL: string; const ASource: TStream; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
  4. function Post(const AURL: string; const ASource: TMultipartFormData; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;

C++

  1. _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 */;
  2. _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 */;
  3. _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 */;
  4. _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

Delphi

function Get(const AURL: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse;

C++

_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>());

我们可以看到官方给与的这个新控件的定义及使用也很简单,下面我们自己创建个单元进行更深入的测试 

  1. unit Unit1;
  2. interface
  3. uses
  4. Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  5. System.Classes, Vcl.Graphics,
  6. Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Net.URLClient,
  7. System.Net.HttpClient, System.Net.HttpClientComponent, Vcl.StdCtrls;
  8. type
  9. TForm1 = class(TForm)
  10. NetHTTPClient1: TNetHTTPClient;
  11. Button1: TButton;
  12. Memo1: TMemo;
  13. Button2: TButton;
  14. NetHTTPClient2: TNetHTTPClient;
  15. Button3: TButton;
  16. procedure Button1Click(Sender: TObject);
  17. procedure NetHTTPClient1RequestCompleted(const Sender: TObject;
  18. const AResponse: IHTTPResponse);
  19. procedure Button2Click(Sender: TObject);
  20. procedure NetHTTPClient2RequestCompleted(const Sender: TObject;
  21. const AResponse: IHTTPResponse);
  22. procedure Button3Click(Sender: TObject);
  23. private
  24. { Private declarations }
  25. public
  26. { Public declarations }
  27. end;
  28. var
  29. Form1: TForm1;
  30. implementation
  31. uses System.NetEncoding;
  32. {$R *.dfm}
  33. function UrlDecode(const AStr: AnsiString): AnsiString;
  34. var
  35. Sp, Rp, Cp: PAnsiChar;
  36. s: AnsiString;
  37. begin
  38. SetLength(Result, Length(AStr));
  39. Sp := PAnsiChar(AStr);
  40. Rp := PAnsiChar(Result);
  41. Cp := Sp;
  42. while Sp^ <> #0 do
  43. begin
  44. case Sp^ of
  45. '+':
  46. Rp^ := ' ';
  47. '%':
  48. begin
  49. Inc(Sp);
  50. if Sp^ = '%' then
  51. Rp^ := '%'
  52. else
  53. begin
  54. Cp := Sp;
  55. Inc(Sp);
  56. if (Cp^ <> #0) and (Sp^ <> #0) then
  57. begin
  58. s := AnsiChar('$') + Cp^ + Sp^;
  59. Rp^ := AnsiChar(StrToInt(string(s)));
  60. end;
  61. end;
  62. Cp := Cp;
  63. end;
  64. else
  65. Rp^ := Sp^;
  66. end;
  67. Inc(Rp);
  68. Inc(Sp);
  69. end;
  70. SetLength(Result, Rp - PAnsiChar(Result));
  71. end;
  72. procedure TForm1.Button1Click(Sender: TObject);
  73. var
  74. vHttp: TNetHTTPClient;
  75. vUTF8, vGBK: TStringStream;
  76. begin
  77. vHttp := TNetHTTPClient.Create(nil);
  78. vUTF8 := TStringStream.Create('', TEncoding.GetEncoding(65001));
  79. vGBK := TStringStream.Create('', TEncoding.GetEncoding(936));
  80. try
  81. Memo1.Lines.Add('----------------阻塞----------------');
  82. with vHttp do
  83. begin
  84. vUTF8.Clear;
  85. ConnectionTimeout := 2000; // 2秒
  86. ResponseTimeout := 10000; // 10秒
  87. AcceptCharSet := 'utf-8';
  88. AcceptEncoding := '65001';
  89. AcceptLanguage := 'zh-CN';
  90. ContentType := 'text/html';
  91. UserAgent := 'Embarcadero URI Client/1.0';
  92. try
  93. Get('http://offeu.com/utf8.txt', vUTF8);
  94. Memo1.Lines.Add('utf8:' + TNetEncoding.URL.UrlDecode(vUTF8.DataString));
  95. except
  96. on E: Exception do
  97. // Error sending data: (12002) 操作超时.
  98. // Error receiving data: (12002) 操作超时
  99. if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error sending data'
  100. then
  101. Memo1.Lines.Add('utf8:连接失败!')
  102. else if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error receiving data'
  103. then
  104. Memo1.Lines.Add('utf8:接收失败,请延长接收超时时间!')
  105. else
  106. Memo1.Lines.Add('utf8:' + E.Message);
  107. end;
  108. vGBK.Clear;
  109. AcceptCharSet := 'gbk';
  110. AcceptEncoding := '936';
  111. AcceptLanguage := 'zh-CN';
  112. ContentType := 'text/html';
  113. UserAgent := 'Embarcadero URI Client/1.0';
  114. Get('http://offeu.com/gbk.txt', vGBK);
  115. Memo1.Lines.Add('gbk:' + string(UrlDecode(AnsiString(vGBK.DataString))));
  116. end;
  117. Memo1.Lines.Add('----------------异步----------------');
  118. with NetHTTPClient1 do
  119. begin
  120. Asynchronous := true;
  121. ConnectionTimeout := 10000; // 10秒
  122. ResponseTimeout := 10000; // 10秒
  123. AcceptCharSet := 'utf-8';
  124. AcceptEncoding := '65001';
  125. AcceptLanguage := 'zh-CN';
  126. ContentType := 'text/html';
  127. UserAgent := 'Embarcadero URI Client/1.0';
  128. Get('http://offeu.com/utf8.txt');
  129. end;
  130. finally
  131. vUTF8.Free;
  132. vGBK.Free;
  133. vHttp.Free;
  134. end;
  135. end;
  136. procedure TForm1.Button2Click(Sender: TObject);
  137. var
  138. vHttp: TNetHTTPClient;
  139. vS: TStringStream;
  140. begin
  141. // 这里用的 APPCODE 是阿里云市场中的api,需要申请。
  142. vHttp := TNetHTTPClient.Create(nil);
  143. vS := TStringStream.Create('', TEncoding.GetEncoding(65001));
  144. try
  145. with vHttp do
  146. begin
  147. Memo1.Lines.Add('--------------SSL阻塞--------------');
  148. vS.Clear;
  149. ConnectionTimeout := 10000; // 10秒
  150. ResponseTimeout := 10000; // 10秒
  151. CustomHeaders['Authorization'] :=
  152. 'APPCODE 你申请的appcode';
  153. Accept := 'application/json;';
  154. ContentType := 'application/json; charset=utf-8;';
  155. UserAgent := 'Embarcadero URI Client/1.0';
  156. Get('https://dm-81.data.aliyun.com/rest/160601/ip/getIpInfo.json?'
  157. + 'ip=60.191.244.5', vS);
  158. Memo1.Lines.Add('ssl:'
  159. + string(TNetEncoding.URL.UrlDecode(vS.DataString)));
  160. end;
  161. finally
  162. vS.Free;
  163. vHttp.Free;
  164. end;
  165. Memo1.Lines.Add('--------------SSL异步--------------');
  166. with NetHTTPClient2 do
  167. begin
  168. Asynchronous := true;
  169. ConnectionTimeout := 10000; // 10秒
  170. ResponseTimeout := 10000; // 10秒
  171. CustomHeaders['Authorization'] :=
  172. 'APPCODE 你申请的appcode';
  173. Accept := 'application/json;';
  174. ContentType := 'application/json; charset=utf-8;';
  175. UserAgent := 'Embarcadero URI Client/1.0';
  176. Get('https://dm-81.data.aliyun.com/rest/160601/ip/getIpInfo.json?'
  177. + 'ip=60.191.244.5');
  178. end;
  179. end;
  180. procedure TForm1.Button3Click(Sender: TObject);
  181. var
  182. vHttp: TNetHTTPClient;
  183. vS: TStringStream;
  184. vList: TStrings;
  185. begin
  186. vHttp := TNetHTTPClient.Create(nil);
  187. vList := TStringList.Create;
  188. vS := TStringStream.Create;
  189. try
  190. Memo1.Lines.Add('----------------Post阻塞----------------');
  191. vS.Clear;
  192. with vHttp do
  193. begin
  194. ConnectionTimeout := 2000; // 2秒
  195. ResponseTimeout := 10000; // 10秒
  196. AcceptCharSet := 'utf-8';
  197. AcceptEncoding := '65001';
  198. AcceptLanguage := 'zh-CN';
  199. ContentType := 'text/html';
  200. UserAgent := 'Embarcadero URI Client/1.0';
  201. vList.Clear;
  202. vList.Values['id'] := 'test';
  203. vList.Values['pwd'] := 'test';
  204. vList.Values['cmd'] := '1';
  205. try
  206. Post('http://60.191.220.219:8090', vList, vS); // utf8进gbk出
  207. // Memo1.Lines.Add('post:' + TNetEncoding.URL.UrlDecode(vS.DataString));
  208. Memo1.Lines.Add('post:' + vS.DataString);
  209. except
  210. on E: Exception do
  211. // Error sending data: (12002) 操作超时.
  212. // Error receiving data: (12002) 操作超时
  213. if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error sending data'
  214. then
  215. Memo1.Lines.Add('post:连接失败!')
  216. else if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error receiving data'
  217. then
  218. Memo1.Lines.Add('post:接收失败,请延长接收超时时间!')
  219. else
  220. Memo1.Lines.Add('post:' + E.Message);
  221. end;
  222. end;
  223. finally
  224. vS.Free;
  225. vList.Free;
  226. vHttp.Free;
  227. end;
  228. end;
  229. procedure TForm1.NetHTTPClient1RequestCompleted(const Sender: TObject;
  230. const AResponse: IHTTPResponse);
  231. begin
  232. Memo1.Lines.Add('utf8:' + TNetEncoding.URL.UrlDecode(
  233. AResponse.ContentAsString(TEncoding.GetEncoding(65001))));
  234. end;
  235. procedure TForm1.NetHTTPClient2RequestCompleted(const Sender: TObject;
  236. const AResponse: IHTTPResponse);
  237. begin
  238. Memo1.Lines.Add('ssl:' + TNetEncoding.URL.UrlDecode(
  239. AResponse.ContentAsString(TEncoding.GetEncoding(65001))));
  240. end;
  241. end.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/767987
推荐阅读
相关标签
  

闽ICP备14008679号