/
ALHttpClient.pas
3044 lines (2810 loc) · 97.7 KB
/
ALHttpClient.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{ *************************************************************
www: http://sourceforge.net/projects/alcinoe/
svn: svn checkout svn://svn.code.sf.net/p/alcinoe/code/ alcinoe-code
Author(s): Stéphane Vander Clock (alcinoe@arkadia.com)
Sponsor(s): Arkadia SA (http://www.arkadia.com)
product: ALHttpClient Base Class
Version: 4.00
Description: TALHttpClient is a ancestor of class like
TALWinInetHttpClient or TALWinHttpClient
Legal issues: Copyright (C) 1999-2013 by Arkadia Software Engineering
This software is provided 'as-is', without any express
or implied warranty. In no event will the author be
held liable for any damages arising from the use of
this software.
Permission is granted to anyone to use this software
for any purpose, including commercial applications,
and to alter it and redistribute it freely, subject
to the following restrictions:
1. The origin of this software must not be
misrepresented, you must not claim that you wrote
the original software. If you use this software in
a product, an acknowledgment in the product
documentation would be appreciated but is not
required.
2. Altered source versions must be plainly marked as
such, and must not be misrepresented as being the
original software.
3. This notice may not be removed or altered from any
source distribution.
4. You must register this software by sending a picture
postcard to the author. Use a nice stamp and mention
your name, street address, EMail address and any
comment you like to say.
Know bug :
History : 28/11/2005: move public procedure to published
in TALHttpClientProxyParams
26/06/2012: Add xe2 support
Link : http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.1
http://www.ietf.org/rfc/rfc1867.txt
http://www.ietf.org/rfc/rfc2388.txt
http://www.w3.org/MarkUp/html-spec/html-spec_8.html
http://www.cs.tut.fi/~jkorpela/forms/methods.html
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
http://wp.netscape.com/newsref/std/cookie_spec.html
* Please send all your feedback to alcinoe@arkadia.com
* If you have downloaded this source from a website different from
sourceforge.net, please get the last version on http://sourceforge.net/projects/alcinoe/
* Please, help us to keep the development of these components free by
promoting the sponsor on http://static.arkadia.com/html/alcinoe_like.html
************************************************************** }
unit ALHttpClient;
interface
{$IF CompilerVersion >= 25} { Delphi XE4 }
{$LEGACYIFEND ON} // http://docwiki.embarcadero.com/RADStudio/XE4/en/Legacy_IFEND_(Delphi)
{$IFEND}
uses {$IF CompilerVersion >= 28} {Delphi XE2}
System.SysUtils,
System.Classes,
System.NetEncoding,
Winapi.Wininet,
{$ELSE}
SysUtils,
Classes,
Wininet,
{$IFEND}
ALStringList,
ALMultiPartParser;
type
{ -- onchange Event that specify the property index that is just changed -- }
TALHTTPPropertyChangeEvent = procedure(sender: Tobject;
Const PropertyIndex: Integer) of object;
{ --protocol version-- }
TALHTTPProtocolVersion = (HTTPpv_1_0, HTTPpv_1_1);
{ --Request method-- }
TALHTTPMethod = (HTTPmt_Get, HTTPmt_Post, HTTPmt_Head, HTTPmt_Trace,
HTTPmt_Put, HTTPmt_Delete);
{ --Request header-- }
TALHTTPRequestHeader = Class(Tobject)
Private
fAccept: AnsiString;
fAcceptCharSet: AnsiString;
fAcceptEncoding: AnsiString;
fAcceptLanguage: AnsiString;
fAllow: AnsiString;
fAuthorization: AnsiString;
fCacheControl: AnsiString;
fConnection: AnsiString;
fContentEncoding: AnsiString;
fContentLanguage: AnsiString;
fContentLength: AnsiString;
fContentLocation: AnsiString;
fContentMD5: AnsiString;
fContentRange: AnsiString;
fContentType: AnsiString;
fDate: AnsiString;
fExpect: AnsiString;
fExpires: AnsiString;
fFrom: AnsiString;
fHost: AnsiString;
fIfMatch: AnsiString;
fIfModifiedSince: AnsiString;
fIfNoneMatch: AnsiString;
fIfRange: AnsiString;
fIfUnmodifiedSince: AnsiString;
fLastModified: AnsiString;
fMaxForwards: AnsiString;
fPragma: AnsiString;
fProxyAuthorization: AnsiString;
fRange: AnsiString;
fReferer: AnsiString;
fTE: AnsiString;
fTrailer: AnsiString;
fTransferEncoding: AnsiString;
fUpgrade: AnsiString;
fUserAgent: AnsiString;
fVia: AnsiString;
fWarning: AnsiString;
FCustomHeaders: TALStrings;
FCookies: TALStrings;
FOnChange: TALHTTPPropertyChangeEvent;
Procedure DoChange(PropertyIndex: Integer);
procedure SetHeaderValueByPropertyIndex(const Index: Integer;
const Value: AnsiString);
Function GetRawHeaderText: AnsiString;
procedure SetCookies(const Value: TALStrings);
procedure SetRawHeaderText(const aRawHeaderText: AnsiString);
procedure SetCustomHeaders(const Value: TALStrings);
public
constructor Create; virtual;
destructor Destroy; override;
procedure Clear;
Property RawHeaderText: AnsiString read GetRawHeaderText
write SetRawHeaderText;
property Accept: AnsiString index 0 read fAccept
write SetHeaderValueByPropertyIndex;
{ Accept: audio/*; q=0.2, audio/basic }
property AcceptCharSet: AnsiString index 1 read fAcceptCharSet
write SetHeaderValueByPropertyIndex;
{ Accept-Charset: iso-8859-5, unicode-1-1;q=0.8 }
property AcceptEncoding: AnsiString index 2 read fAcceptEncoding
write SetHeaderValueByPropertyIndex;
{ Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0 }
property AcceptLanguage: AnsiString index 3 read fAcceptLanguage
write SetHeaderValueByPropertyIndex;
{ Accept-Language: da, en-gb;q=0.8, en;q=0.7 }
property Allow: AnsiString index 4 read fAllow
write SetHeaderValueByPropertyIndex; { Allow: GET, HEAD, PUT }
property Authorization: AnsiString index 5 read fAuthorization
write SetHeaderValueByPropertyIndex;
{ Authorization: BASIC d2VibWFzdGVyOnpycW1hNHY= }
property CacheControl: AnsiString index 6 read fCacheControl
write SetHeaderValueByPropertyIndex; { Cache-Control: no-cache }
property Connection: AnsiString index 7 read fConnection
write SetHeaderValueByPropertyIndex; { Connection: close }
property ContentEncoding: AnsiString index 8 read fContentEncoding
write SetHeaderValueByPropertyIndex; { Content-Encoding: gzip }
property ContentLanguage: AnsiString index 9 read fContentLanguage
write SetHeaderValueByPropertyIndex; { Content-Language: mi, en }
property ContentLength: AnsiString index 10 read fContentLength
write SetHeaderValueByPropertyIndex; { Content-Length: 3495 }
property ContentLocation: AnsiString index 11 read fContentLocation
write SetHeaderValueByPropertyIndex;
{ Content-Location: http://localhost/page.asp }
property ContentMD5: AnsiString index 12 read fContentMD5
write SetHeaderValueByPropertyIndex; { Content-MD5: [md5-digest] }
property ContentRange: AnsiString index 13 read fContentRange
write SetHeaderValueByPropertyIndex;
{ Content-Range: bytes 2543-4532/7898 }
property ContentType: AnsiString index 14 read fContentType
write SetHeaderValueByPropertyIndex;
{ Content-Type: text/html; charset=ISO-8859-4 }
property Date: AnsiString index 15 read fDate
write SetHeaderValueByPropertyIndex;
{ Date: Tue, 15 Nov 1994 08:12:31 GMT }
property Expect: AnsiString index 16 read fExpect
write SetHeaderValueByPropertyIndex; { Expect: 100-continue }
property Expires: AnsiString index 17 read fExpires
write SetHeaderValueByPropertyIndex;
{ Expires: Thu, 01 Dec 1994 16:00:00 GMT }
property From: AnsiString index 18 read fFrom
write SetHeaderValueByPropertyIndex; { From: webmaster@w3.org }
property Host: AnsiString index 19 read fHost
write SetHeaderValueByPropertyIndex; { Host: www.w3.org }
property IfMatch: AnsiString index 20 read fIfMatch
write SetHeaderValueByPropertyIndex; { If-Match: entity_tag001 }
property IfModifiedSince: AnsiString index 21 read fIfModifiedSince
write SetHeaderValueByPropertyIndex;
{ If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT }
property IfNoneMatch: AnsiString index 22 read fIfNoneMatch
write SetHeaderValueByPropertyIndex; { If-None-Match: entity_tag001 }
property IfRange: AnsiString index 23 read fIfRange
write SetHeaderValueByPropertyIndex; { If-Range: entity_tag001 }
property IfUnmodifiedSince: AnsiString index 24 read fIfUnmodifiedSince
write SetHeaderValueByPropertyIndex;
{ If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT }
property LastModified: AnsiString index 25 read fLastModified
write SetHeaderValueByPropertyIndex;
{ Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT }
property MaxForwards: AnsiString index 26 read fMaxForwards
write SetHeaderValueByPropertyIndex; { Max-Forwards: 3 }
property Pragma: AnsiString index 27 read fPragma
write SetHeaderValueByPropertyIndex; { Pragma: no-cache }
property ProxyAuthorization: AnsiString index 28 read fProxyAuthorization
write SetHeaderValueByPropertyIndex;
{ Proxy-Authorization: [credentials] }
property Range: AnsiString index 29 read fRange
write SetHeaderValueByPropertyIndex; { Range: bytes=100-599 }
property Referer: AnsiString index 30 read fReferer
write SetHeaderValueByPropertyIndex;
{ Referer: http://www.w3.org/hypertext/DataSources/Overview.html }
property TE: AnsiString index 31 read fTE
write SetHeaderValueByPropertyIndex; { TE: trailers, deflate;q=0.5 }
property Trailer: AnsiString index 32 read fTrailer
write SetHeaderValueByPropertyIndex; { Trailer: Date }
property TransferEncoding: AnsiString index 33 read fTransferEncoding
write SetHeaderValueByPropertyIndex; { Transfer-Encoding: chunked }
property Upgrade: AnsiString index 34 read fUpgrade
write SetHeaderValueByPropertyIndex;
{ Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 }
property UserAgent: AnsiString index 35 read fUserAgent
write SetHeaderValueByPropertyIndex;
{ User-Agent: CERN-LineMode/2.15 libwww/2.17b3 }
property Via: AnsiString index 36 read fVia
write SetHeaderValueByPropertyIndex;
{ Via: 1.0 ricky, 1.1 mertz, 1.0 lucy }
property Warning: AnsiString index 37 read fWarning
write SetHeaderValueByPropertyIndex;
{ Warning: 112 Disconnected Operation }
property CustomHeaders: TALStrings read FCustomHeaders
write SetCustomHeaders;
property Cookies: TALStrings read FCookies write SetCookies;
property OnChange: TALHTTPPropertyChangeEvent read FOnChange
write FOnChange;
end;
{ --TALHTTPCookie-- }
TALHTTPCookie = class(TCollectionItem)
private
FName: AnsiString;
FValue: AnsiString;
FPath: AnsiString;
FDomain: AnsiString;
fExpires: TDateTime;
FSecure: Boolean;
protected
function GetHeaderValue: AnsiString;
procedure SetHeaderValue(Const aValue: AnsiString);
public
constructor Create(Collection: TCollection); override;
procedure AssignTo(Dest: TPersistent); override;
property Name: AnsiString read FName write FName;
property Value: AnsiString read FValue write FValue;
property Domain: AnsiString read FDomain write FDomain;
property Path: AnsiString read FPath write FPath;
property Expires: TDateTime read fExpires write fExpires;
property Secure: Boolean read FSecure write FSecure;
property HeaderValue: AnsiString read GetHeaderValue write SetHeaderValue;
end;
{ --TALCookieCollection-- }
TALHTTPCookieCollection = class(TCollection)
private
protected
function GetCookie(Index: Integer): TALHTTPCookie;
procedure SetCookie(Index: Integer; Cookie: TALHTTPCookie);
public
function Add: TALHTTPCookie;
property Items[Index: Integer]: TALHTTPCookie read GetCookie
write SetCookie; default;
end;
{ --Response header-- }
TALHTTPResponseHeader = Class(Tobject)
Private
FAcceptRanges: AnsiString;
FAge: AnsiString;
fAllow: AnsiString;
fCacheControl: AnsiString;
fConnection: AnsiString;
fContentEncoding: AnsiString;
fContentLanguage: AnsiString;
fContentLength: AnsiString;
fContentLocation: AnsiString;
fContentMD5: AnsiString;
fContentRange: AnsiString;
fContentType: AnsiString;
fDate: AnsiString;
FETag: AnsiString;
fExpires: AnsiString;
fLastModified: AnsiString;
FLocation: AnsiString;
fPragma: AnsiString;
FProxyAuthenticate: AnsiString;
FRetryAfter: AnsiString;
FServer: AnsiString;
fTrailer: AnsiString;
fTransferEncoding: AnsiString;
fUpgrade: AnsiString;
FVary: AnsiString;
fVia: AnsiString;
fWarning: AnsiString;
FWWWAuthenticate: AnsiString;
FRawHeaderText: AnsiString;
FCustomHeaders: TALStrings;
FCookies: TALHTTPCookieCollection;
FStatusCode: AnsiString;
FHttpProtocolVersion: AnsiString;
FReasonPhrase: AnsiString;
procedure SetRawHeaderText(const aRawHeaderText: AnsiString);
Function GetRawHeaderText: AnsiString;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Clear;
property AcceptRanges: AnsiString read FAcceptRanges;
{ Accept-Ranges: bytes }
property Age: AnsiString read FAge; { Age: 2147483648(2^31) }
property Allow: AnsiString read fAllow; { Allow: GET, HEAD, PUT }
property CacheControl: AnsiString read fCacheControl;
{ Cache-Control: no-cache }
property Connection: AnsiString read fConnection; { Connection: close }
property ContentEncoding: AnsiString read fContentEncoding;
{ Content-Encoding: gzip }
property ContentLanguage: AnsiString read fContentLanguage;
{ Content-Language: mi, en }
property ContentLength: AnsiString read fContentLength;
{ Content-Length: 3495 }
property ContentLocation: AnsiString read fContentLocation;
{ Content-Location: http://localhost/page.asp }
property ContentMD5: AnsiString read fContentMD5;
{ Content-MD5: [md5-digest] }
property ContentRange: AnsiString read fContentRange;
{ Content-Range: bytes 2543-4532/7898 }
property ContentType: AnsiString read fContentType;
{ Content-Type: text/html; charset=ISO-8859-4 }
property Date: AnsiString read fDate;
{ Date: Tue, 15 Nov 1994 08:12:31 GMT }
property ETag: AnsiString read FETag; { ETag: W/"xyzzy" }
property Expires: AnsiString read fExpires;
{ Expires: Thu, 01 Dec 1994 16:00:00 GMT }
property LastModified: AnsiString read fLastModified;
{ Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT }
property Location: AnsiString read FLocation;
{ Location: http://www.w3.org/pub/WWW/People.html }
property Pragma: AnsiString read fPragma; { Pragma: no-cache }
property ProxyAuthenticate: AnsiString read FProxyAuthenticate;
{ Proxy-Authenticate: [challenge] }
property RetryAfter: AnsiString read FRetryAfter;
{ Retry-After: Fri, 31 Dec 1999 23:59:59 GMT }
property Server: AnsiString read FServer; { Server: CERN/3.0 libwww/2.17 }
property Trailer: AnsiString read fTrailer; { Trailer: Date }
property TransferEncoding: AnsiString read fTransferEncoding;
{ Transfer-Encoding: chunked }
property Upgrade: AnsiString read fUpgrade;
{ Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 }
property Vary: AnsiString read FVary; { Vary: Date }
property Via: AnsiString read fVia; { Via: 1.0 ricky, 1.1 mertz, 1.0 lucy }
property Warning: AnsiString read fWarning;
{ Warning: 112 Disconnected Operation }
property WWWAuthenticate: AnsiString read FWWWAuthenticate;
{ WWW-Authenticate: [challenge] }
Property CustomHeaders: TALStrings read FCustomHeaders;
Property Cookies: TALHTTPCookieCollection read FCookies;
property StatusCode: AnsiString read FStatusCode;
property HttpProtocolVersion: AnsiString read FHttpProtocolVersion;
Property ReasonPhrase: AnsiString read FReasonPhrase;
property RawHeaderText: AnsiString read GetRawHeaderText
write SetRawHeaderText;
end;
{ --------------------------------------- }
EALHTTPClientException = class(Exception)
private
FStatusCode: Integer;
public
constructor Create(const Msg: AnsiString; SCode: Integer = 0);
constructor CreateFmt(const Msg: AnsiString; const Args: array of const;
SCode: Integer = 0);
property StatusCode: Integer read FStatusCode write FStatusCode;
end;
{ --------------------------------------- }
TALHTTPClientProxyParams = Class(Tobject)
Private
FProxyBypass: AnsiString;
FproxyServer: AnsiString;
FProxyUserName: AnsiString;
FProxyPassword: AnsiString;
FproxyPort: Integer;
FOnChange: TALHTTPPropertyChangeEvent;
procedure SetProxyBypass(const Value: AnsiString);
procedure SetProxyPassword(const Value: AnsiString);
procedure SetProxyPort(const Value: Integer);
procedure SetProxyServer(const Value: AnsiString);
procedure SetProxyUserName(const Value: AnsiString);
Procedure DoChange(PropertyIndex: Integer);
public
constructor Create; virtual;
procedure Clear;
Property ProxyBypass: AnsiString read FProxyBypass write SetProxyBypass;
// index 0
property ProxyServer: AnsiString read FproxyServer write SetProxyServer;
// index 1
property ProxyPort: Integer read FproxyPort write SetProxyPort default 0;
// index 2
property ProxyUserName: AnsiString read FProxyUserName
write SetProxyUserName; // index 3
property ProxyPassword: AnsiString read FProxyPassword
write SetProxyPassword; // index 4
property OnChange: TALHTTPPropertyChangeEvent read FOnChange
write FOnChange;
end;
{ -------------------------------------------------------------------------------------------------- }
TAlHTTPClientRedirectEvent = procedure(sender: Tobject;
const NewURL: AnsiString) of object;
TALHTTPClientUploadProgressEvent = procedure(sender: Tobject; Sent: Integer;
Total: Integer) of object;
TALHTTPClientDownloadProgressEvent = procedure(sender: Tobject; Read: Integer;
Total: Integer) of object;
{ ---------------------------- }
TALHTTPClient = class(Tobject)
private
FProxyParams: TALHTTPClientProxyParams;
FRequestHeader: TALHTTPRequestHeader;
FProtocolVersion: TALHTTPProtocolVersion;
FRequestMethod: TALHTTPMethod;
FURL: AnsiString;
FUserName: AnsiString;
FPassword: AnsiString;
FConnectTimeout: Integer;
FSendTimeout: Integer;
FReceiveTimeout: Integer;
FOnUploadProgress: TALHTTPClientUploadProgressEvent;
FOnDownloadProgress: TALHTTPClientDownloadProgressEvent;
FOnRedirect: TAlHTTPClientRedirectEvent;
FUploadBufferSize: Integer;
protected
procedure SetURL(const Value: AnsiString); virtual;
procedure SetUsername(const NameValue: AnsiString); virtual;
procedure SetPassword(const PasswordValue: AnsiString); virtual;
procedure OnProxyParamsChange(sender: Tobject;
Const PropertyIndex: Integer); virtual;
procedure OnRequestHeaderChange(sender: Tobject;
Const PropertyIndex: Integer); virtual;
procedure SetUploadBufferSize(const Value: Integer); virtual;
procedure SetOnRedirect(const Value: TAlHTTPClientRedirectEvent); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Execute(aRequestDataStream: TStream;
aResponseContentStream: TStream;
aResponseContentHeader: TALHTTPResponseHeader); virtual;
Procedure Get(const aUrl: AnsiString; aResponseContentStream: TStream;
aResponseContentHeader: TALHTTPResponseHeader); overload;
Procedure Post(const aUrl: AnsiString; aResponseContentStream: TStream;
aResponseContentHeader: TALHTTPResponseHeader); overload;
Procedure Post(const aUrl: AnsiString; aPostDataStream: TStream;
aResponseContentStream: TStream;
aResponseContentHeader: TALHTTPResponseHeader); overload;
Procedure PostUrlEncoded(const aUrl: AnsiString;
aPostDataStrings: TALStrings; aResponseContentStream: TStream;
aResponseContentHeader: TALHTTPResponseHeader;
Const EncodeParams: Boolean = True); overload;
Procedure PostMultipartFormData(const aUrl: AnsiString;
aPostDataStrings: TALStrings;
aPostDataFiles: TALMultiPartFormDataContents;
aResponseContentStream: TStream;
aResponseContentHeader: TALHTTPResponseHeader); overload;
Procedure Head(const aUrl: AnsiString; aResponseContentStream: TStream;
aResponseContentHeader: TALHTTPResponseHeader); overload;
Procedure Trace(const aUrl: AnsiString; aResponseContentStream: TStream;
aResponseContentHeader: TALHTTPResponseHeader); overload;
Procedure Put(const aUrl: AnsiString; aPutDataStream: TStream;
aResponseContentStream: TStream;
aResponseContentHeader: TALHTTPResponseHeader); overload;
procedure Delete(const aUrl: AnsiString; aResponseContentStream: TStream;
aResponseContentHeader: TALHTTPResponseHeader); overload;
Function Get(const aUrl: AnsiString): AnsiString; overload;
Function Get(const aUrl: AnsiString; aParams: TALStrings;
Const EncodeParams: Boolean = True): AnsiString; overload;
Procedure Get(const aUrl: AnsiString; aParams: TALStrings;
aResponseContentStream: TStream;
aResponseContentHeader: TALHTTPResponseHeader;
Const EncodeParams: Boolean = True); overload;
Function Post(const aUrl: AnsiString): AnsiString; overload;
Function Post(const aUrl: AnsiString; aPostDataStream: TStream)
: AnsiString; overload;
Function PostUrlEncoded(const aUrl: AnsiString;
aPostDataStrings: TALStrings; Const EncodeParams: Boolean = True)
: AnsiString; overload;
Function PostMultipartFormData(const aUrl: AnsiString;
aPostDataStrings: TALStrings;
aPostDataFiles: TALMultiPartFormDataContents): AnsiString; overload;
Function Head(const aUrl: AnsiString): AnsiString; overload;
Function Trace(const aUrl: AnsiString): AnsiString; overload;
function Put(const aUrl: AnsiString; aPutDataStream: TStream)
: AnsiString; overload;
function Delete(const aUrl: AnsiString): AnsiString; overload;
property URL: AnsiString read FURL write SetURL;
property ConnectTimeout: Integer read FConnectTimeout write FConnectTimeout
default 0;
property SendTimeout: Integer read FSendTimeout write FSendTimeout
default 0;
property ReceiveTimeout: Integer read FReceiveTimeout write FReceiveTimeout
default 0;
property UploadBufferSize: Integer read FUploadBufferSize
write SetUploadBufferSize default $8000;
property ProxyParams: TALHTTPClientProxyParams read FProxyParams;
property RequestHeader: TALHTTPRequestHeader read FRequestHeader;
Property ProtocolVersion: TALHTTPProtocolVersion read FProtocolVersion
write FProtocolVersion default HTTPpv_1_1;
Property RequestMethod: TALHTTPMethod read FRequestMethod
write FRequestMethod default HTTPmt_Get;
property UserName: AnsiString read FUserName write SetUsername;
property Password: AnsiString read FPassword write SetPassword;
property OnUploadProgress: TALHTTPClientUploadProgressEvent
read FOnUploadProgress write FOnUploadProgress;
property OnDownloadProgress: TALHTTPClientDownloadProgressEvent
read FOnDownloadProgress write FOnDownloadProgress;
property OnRedirect: TAlHTTPClientRedirectEvent read FOnRedirect
write SetOnRedirect;
end;
{ Http Function }
function ALHTTPDecode(const AStr: AnsiString): AnsiString;
procedure ALHTTPEncodeParamNameValues(ParamValues: TALStrings);
procedure ALExtractHTTPFields(Separators, WhiteSpace, Quotes: TSysCharSet;
Content: PAnsiChar; Strings: TALStrings; StripQuotes: Boolean = False);
procedure ALExtractHeaderFields(Separators, WhiteSpace, Quotes: TSysCharSet;
Content: PAnsiChar; Strings: TALStrings; Decode: Boolean;
StripQuotes: Boolean = False);
procedure ALExtractHeaderFieldsWithQuoteEscaped(Separators, WhiteSpace,
Quotes: TSysCharSet; Content: PAnsiChar; Strings: TALStrings; Decode: Boolean;
StripQuotes: Boolean = False);
Function AlRemoveShemeFromUrl(aUrl: AnsiString): AnsiString;
Function AlExtractShemeFromUrl(aUrl: AnsiString): TInternetScheme;
Function AlExtractHostNameFromUrl(aUrl: AnsiString): AnsiString;
Function AlExtractDomainNameFromUrl(aUrl: AnsiString): AnsiString;
Function AlExtractUrlPathFromUrl(aUrl: AnsiString): AnsiString;
Function AlInternetCrackUrl(aUrl: AnsiString;
Var SchemeName, HostName, UserName, Password, UrlPath, ExtraInfo: AnsiString;
var PortNumber: Integer): Boolean; overload;
Function AlInternetCrackUrl(aUrl: AnsiString;
Var SchemeName, HostName, UserName, Password, UrlPath, Anchor: AnsiString;
// not the anchor is never send to the server ! it's only used on client side
Query: TALStrings; var PortNumber: Integer): Boolean; overload;
Function AlInternetCrackUrl(var URL: AnsiString; // if true return UrlPath
var Anchor: AnsiString; Query: TALStrings): Boolean; overload;
Function AlRemoveAnchorFromUrl(aUrl: AnsiString; Var aAnchor: AnsiString)
: AnsiString; overload;
Function AlRemoveAnchorFromUrl(aUrl: AnsiString): AnsiString; overload;
function AlCombineUrl(RelativeUrl, BaseUrl: AnsiString): AnsiString; overload;
Function AlCombineUrl(RelativeUrl, BaseUrl, Anchor: AnsiString;
Query: TALStrings): AnsiString; overload;
const
CAlRfc822DayOfWeekNames: array [1 .. 7] of AnsiString = ('Sun', 'Mon', 'Tue',
'Wed', 'Thu', 'Fri', 'Sat');
CALRfc822MonthOfTheYearNames: array [1 .. 12] of AnsiString = ('Jan', 'Feb',
'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
function ALGmtDateTimeToRfc822Str(const aValue: TDateTime): AnsiString;
function ALDateTimeToRfc822Str(const aValue: TDateTime): AnsiString;
Function ALTryRfc822StrToGMTDateTime(const S: AnsiString;
out Value: TDateTime): Boolean;
function ALRfc822StrToGMTDateTime(const S: AnsiString): TDateTime;
Function ALTryIPV4StrToNumeric(aIPv4Str: AnsiString;
var aIPv4Num: Cardinal): Boolean;
Function ALIPV4StrToNumeric(aIPv4: AnsiString): Cardinal;
Function ALNumericToIPv4Str(aIPv4: Cardinal): AnsiString;
type
TALIPv6Binary = array [1 .. 16] of ansiChar;
Function ALZeroIpV6: TALIPv6Binary;
Function ALTryIPV6StrToBinary(aIPv6Str: AnsiString;
var aIPv6Bin: TALIPv6Binary): Boolean;
Function ALIPV6StrTobinary(aIPv6: AnsiString): TALIPv6Binary;
Function ALBinaryToIPv6Str(aIPv6: TALIPv6Binary): AnsiString;
Function ALBinaryStrToIPv6Binary(aIPV6BinaryStr: AnsiString): TALIPv6Binary;
Const
cALHTTPCLient_MsgInvalidURL =
'Invalid url ''%s'' - only supports ''http'' and ''https'' schemes';
cALHTTPCLient_MsgInvalidHTTPRequest = 'Invalid HTTP Request: Length is 0';
cALHTTPCLient_MsgEmptyURL = 'Empty URL';
implementation
uses {$IF CompilerVersion >= 23} {Delphi XE2}
Winapi.Windows,
Web.HttpApp,
System.DateUtils,
System.SysConst,
{$ELSE}
Windows,
HttpApp,
DateUtils,
SysConst,
{$IFEND}
AlMisc,
ALString;
{ *********************************************************************************** }
function AlStringFetch(var AInput: AnsiString; const ADelim: AnsiString)
: AnsiString;
var
LPos: Integer;
begin
LPos := AlPos(ADelim, AInput);
if LPos <= 0 then
begin
Result := AInput;
AInput := '';
end
else
begin
Result := AlCopyStr(AInput, 1, LPos - 1);
AInput := AlCopyStr(AInput, LPos + Length(ADelim), MaxInt);
end;
end;
{ ******************************************************** }
constructor TALHTTPCookie.Create(Collection: TCollection);
begin
inherited Create(Collection);
FName := '';
FValue := '';
FPath := '';
FDomain := '';
fExpires := -1;
FSecure := False;
end;
{ ************************************************** }
procedure TALHTTPCookie.AssignTo(Dest: TPersistent);
begin
if Dest is TALHTTPCookie then
with TALHTTPCookie(Dest) do
begin
Name := Self.FName;
Value := Self.FValue;
Domain := Self.FDomain;
Path := Self.FPath;
Expires := Self.fExpires;
Secure := Self.FSecure;
end
else
inherited AssignTo(Dest);
end;
{ ************************************************ }
function TALHTTPCookie.GetHeaderValue: AnsiString;
begin
{$IF CompilerVersion >= 28}
Result := ALFormat('%s=%s; ', [TNetEncoding.URL.Encode(String(FName)), TNetEncoding.URL.Encode(String(FValue))]);
{$ELSE}
Result := ALFormat('%s=%s; ', [HTTPEncode(FName), HTTPEncode(FValue)]);
{$IFEND}
if Domain <> '' then
Result := Result + ALFormat('domain=%s; ', [Domain]);
if Path <> '' then
Result := Result + ALFormat('path=%s; ', [Path]);
if Expires > -1 then
begin
Result := Result + ALFormat
(ALFormatDateTime('"expires=%s, "dd"-%s-"yyyy" "hh":"nn":"ss" GMT; "',
Expires, ALDefaultFormatSettings),
[CAlRfc822DayOfWeekNames[DayOfWeek(Expires)],
CALRfc822MonthOfTheYearNames[MonthOf(Expires)]]);
end;
if Secure then
Result := Result + 'secure';
if AlCopyStr(Result, Length(Result) - 1, MaxInt) = '; ' then
SetLength(Result, Length(Result) - 2);
end;
{ ***************** }
// exemple of value:
// LSID=DQAAAK
Eaem_vYg; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly
// HSID=AYQEVn
.DKrdst; Domain=.foo.com; Path=/; Expires=Wed, 13-Jan-2021 22:23:01 GMT; HttpOnly
// SSID=Ap4P
.GTEq; Domain=.foo.com; Path=/; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly
procedure TALHTTPCookie.SetHeaderValue(Const aValue: AnsiString);
Var
aCookieProp: TALStringList;
aCookieStr: AnsiString;
begin
FName := '';
FValue := '';
FPath := '';
FDomain := '';
fExpires := -1;
FSecure := False;
aCookieProp := TALStringList.Create;
try
aCookieStr := ALTrim(aValue);
while aCookieStr <> '' do
aCookieProp.Add(ALTrim(AlStringFetch(aCookieStr, ';')));
if aCookieProp.Count = 0 then
exit;
// Exemple of aCookieProp content :
// LSID=DQAAAK
Eaem_vYg
// Domain=docs.foo.com
// Path=/accounts
// Expires=Wed, 13-Jan-2021 22:23:01 GMT
// Secure
// HttpOnly
FName := aCookieProp.Names[0];
FValue := aCookieProp.ValueFromIndex[0];
FPath := aCookieProp.values['PATH'];
if FPath = '' then
FPath := '/';
if not ALTryRfc822StrToGMTDateTime(aCookieProp.values['EXPIRES'], fExpires)
then
fExpires := -1;
FDomain := aCookieProp.values['DOMAIN'];
FSecure := aCookieProp.IndexOf('SECURE') <> -1;
finally
aCookieProp.free;
end;
end;
{ ************************************************** }
function TALHTTPCookieCollection.Add: TALHTTPCookie;
begin
Result := TALHTTPCookie(inherited Add);
end;
{ ************************************************************************ }
function TALHTTPCookieCollection.GetCookie(Index: Integer): TALHTTPCookie;
begin
Result := TALHTTPCookie(inherited Items[Index]);
end;
{ ********************************************************************************* }
procedure TALHTTPCookieCollection.SetCookie(Index: Integer;
Cookie: TALHTTPCookie);
begin
Items[Index].Assign(Cookie);
end;
{ *************************************** }
constructor TALHTTPResponseHeader.Create;
begin
inherited;
FCustomHeaders := TALStringList.Create;
FCustomHeaders.NameValueSeparator := ':';
FCookies := TALHTTPCookieCollection.Create(TALHTTPCookie);
Clear;
end;
{ *************************************** }
destructor TALHTTPResponseHeader.Destroy;
begin
FCustomHeaders.free;
FCookies.free;
inherited;
end;
{ ************************************ }
procedure TALHTTPResponseHeader.Clear;
begin
FAcceptRanges := '';
FAge := '';
fAllow := '';
fCacheControl := '';
fConnection := '';
fContentEncoding := '';
fContentLanguage := '';
fContentLength := '';
fContentLocation := '';
fContentMD5 := '';
fContentRange := '';
fContentType := '';
fDate := '';
FETag := '';
fExpires := '';
fLastModified := '';
FLocation := '';
fPragma := '';
FProxyAuthenticate := '';
FRetryAfter := '';
FServer := '';
fTrailer := '';
fTransferEncoding := '';
fUpgrade := '';
FVary := '';
fVia := '';
fWarning := '';
FWWWAuthenticate := '';
FRawHeaderText := '';
FCustomHeaders.Clear;
FCookies.Clear;
FStatusCode := '';
FHttpProtocolVersion := '';
FReasonPhrase := '';
end;
{ ********************************************************** }
function TALHTTPResponseHeader.GetRawHeaderText: AnsiString;
begin
Result := FRawHeaderText;
end;
{ ********************************************************************************* }
procedure TALHTTPResponseHeader.SetRawHeaderText(Const aRawHeaderText
: AnsiString);
Var
aRawHeaderLst: TALStringList;
j: Integer;
AStatusLine: AnsiString;
{ --------------------------------------------- }
Function AlG001(aName: AnsiString): AnsiString;
Var
i: Integer;
Begin
i := aRawHeaderLst.IndexOfName(aName);
If i >= 0 then
Begin
Result := ALTrim(aRawHeaderLst.ValueFromIndex[i]);
aRawHeaderLst.Delete(i);
end
else
Result := '';
end;
begin
aRawHeaderLst := TALStringList.Create;
try
aRawHeaderLst.NameValueSeparator := ':';
aRawHeaderLst.Text := aRawHeaderText;
FAcceptRanges := AlG001('Accept-Ranges');
FAge := AlG001('Age');
fAllow := AlG001('Allow');
fCacheControl := AlG001('Cache-Control');
fConnection := AlG001('Connection');
fContentEncoding := AlG001('Content-Encoding');
fContentLanguage := AlG001('Content-Language');
fContentLength := AlG001('Content-Length');
fContentLocation := AlG001('Content-Location');
fContentMD5 := AlG001('Content-MD5');
fContentRange := AlG001('Content-Range');
fContentType := AlG001('Content-Type');
fDate := AlG001('Date');
FETag := AlG001('ETag');
fExpires := AlG001('Expires');
fLastModified := AlG001('Last-Modified');
FLocation := AlG001('Location');
fPragma := AlG001('Pragma');
FProxyAuthenticate := AlG001('Proxy-Authenticate');
FRetryAfter := AlG001('Retry-After');
FServer := AlG001('Server');
fTrailer := AlG001('Trailer');
fTransferEncoding := AlG001('Transfer-Encoding');
fUpgrade := AlG001('Upgrade');
FVary := AlG001('Vary');
fVia := AlG001('Via');
fWarning := AlG001('Warning');
FWWWAuthenticate := AlG001('WWW-Authenticate');
FCookies.Clear;
j := aRawHeaderLst.IndexOfName('Set-Cookie');
While j >= 0 do
begin
If ALTrim(aRawHeaderLst.ValueFromIndex[j]) <> '' then
Cookies.Add.HeaderValue := ALTrim(aRawHeaderLst.ValueFromIndex[j]);
aRawHeaderLst.Delete(j);
j := aRawHeaderLst.IndexOfName('Set-Cookie');
end;
If aRawHeaderLst.Count > 0 then
begin
AStatusLine := aRawHeaderLst[0];
// HTTP/1.1 200 OK | 200 OK | status: 200 OK
FHttpProtocolVersion := ALTrim(AlStringFetch(AStatusLine, ' '));
If AlIsInteger(FHttpProtocolVersion) then
begin
FStatusCode := FHttpProtocolVersion;
FHttpProtocolVersion := '';
end
else
FStatusCode := ALTrim(AlStringFetch(AStatusLine, ' '));
FReasonPhrase := ALTrim(AStatusLine);
If not AlIsInteger(FStatusCode) then
begin
FHttpProtocolVersion := '';
AStatusLine := AlG001('Status');
FStatusCode := ALTrim(AlStringFetch(AStatusLine, ' '));
FReasonPhrase := ALTrim(AlStringFetch(AStatusLine, ' '));
end
else
aRawHeaderLst.Delete(0);
end
else
begin
FStatusCode := '';
FHttpProtocolVersion := '';
FReasonPhrase := '';
end;
FCustomHeaders.Clear;
For j := 0 to aRawHeaderLst.Count - 1 do
If ALTrim(aRawHeaderLst[j]) <> '' then
FCustomHeaders.Add(aRawHeaderLst[j]);
FRawHeaderText := aRawHeaderText;
finally
aRawHeaderLst.free;
end;
end;
{ ************************************** }
constructor TALHTTPRequestHeader.Create;
Begin
inherited;
FCustomHeaders := TALStringList.Create;
FCustomHeaders.NameValueSeparator := ':';
FCookies := TALStringList.Create;
FOnChange := nil;
Clear;
fAccept := 'text/html, */*';
end;
{ ************************************** }
destructor TALHTTPRequestHeader.Destroy;
begin
FCustomHeaders.free;
FCookies.free;
inherited;
end;
{ *********************************** }
procedure TALHTTPRequestHeader.Clear;
begin
fAccept := '';
fAcceptCharSet := '';
fAcceptEncoding := '';
fAcceptLanguage := '';
fAllow := '';
fAuthorization := '';
fCacheControl := '';
fConnection := '';
fContentEncoding := '';
fContentLanguage := '';
fContentLength := '';
fContentLocation := '';
fContentMD5 := '';
fContentRange := '';
fContentType := '';
fDate := '';
fExpect := '';
fExpires := '';
fFrom := '';
fHost := '';
fIfMatch := '';
fIfModifiedSince := '';
fIfNoneMatch := '';
fIfRange := '';
fIfUnmodifiedSince := '';
fLastModified := '';
fMaxForwards := '';
fPragma := '';
fProxyAuthorization := '';
fRange := '';
fReferer := '';