-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnitIdHttpThread.pas
121 lines (108 loc) · 2.72 KB
/
UnitIdHttpThread.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
unit UnitIdHttpThread;
interface
uses
Windows, SysUtils, Variants, Classes, Math, IdBaseComponent, IdComponent,
IdTCPConnection, IdTCPClient, IdHTTP,
IdAntiFreezeBase, IdAntiFreeze, IdException;
type
TIdHttpThread = class;
TOnHttpThreadComplete = procedure(thread: TIdHttpThread; msg: string)
of object;
TOnHttpThreadError = procedure(thread: TIdHttpThread; e: Exception) of object;
TIdHttpThreadMode = (ihmHtml, ihmFile);
TIdHttpThread = class(TThread)
private
_http: TIdHTTP;
_mode: TIdHttpThreadMode;
_url: string;
_html: string;
_filename: string;
_key: string;
_OnComplete: TOnHttpThreadComplete;
_OnError: TOnHttpThreadError;
public
constructor Create(http: TIdHTTP);
property OnComplete: TOnHttpThreadComplete read _OnComplete
write _OnComplete;
property OnError: TOnHttpThreadError read _OnError write _OnError;
property Url: string read _url write _url;
property IdHTTP: TIdHTTP read _http write _http;
// 两种模式,1、直接获取html,2、保存到文件
property Mode: TIdHttpThreadMode read _mode write _mode;
// 模式1、直接获取html
property Html: string read _html write _html;
// 模式2、保存到文件
property Filename: string read _filename write _filename;
property Key: string read _key write _key;
protected
procedure Execute; override;
procedure _download;
function _getHtml: String;
end;
implementation
constructor TIdHttpThread.Create(http: TIdHTTP);
begin
inherited Create(true); // 手动启动线程
FreeOnTerminate := true;
_http := http;
end;
procedure TIdHttpThread.Execute;
begin
if Terminated then
exit;
try
try
if _mode = TIdHttpThreadMode.ihmHtml then
begin
_html := self._getHtml;
if Assigned(_OnComplete) then
_OnComplete(self, 'html');
end
else if _mode = TIdHttpThreadMode.ihmFile then
begin
self._download;
if Assigned(_OnComplete) then
_OnComplete(self, 'download');
end;
except
on e: EIdException do
begin
if Assigned(_OnError) then
_OnError(self, e);
end;
end
finally
end;
end;
function TIdHttpThread._getHtml: String;
var
RespData: TStringStream;
begin
RespData := TStringStream.Create('');
try
_http.Get(_url, RespData);
Result := RespData.DataString;
_http.Disconnect;
except
Result := '';
end;
freeandnil(RespData);
end;
procedure TIdHttpThread._download;
var
stream: TFileStream;
begin
stream := TFileStream.Create(_filename, fmCreate);
try
_http.Get(_url, stream);
_http.Disconnect;
freeandnil(stream);
except
on e: Exception do
begin
_http.Disconnect;
freeandnil(stream);
end;
end;
end;
end.