-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathacNetUtils.pas
104 lines (85 loc) · 2.12 KB
/
acNetUtils.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
unit acNetUtils;
interface
uses idHTTP, SysUtils, System.Classes, IdSSL, IdIOHandler;
function getRemoteXmlContent(pUrl: string; http: TIdHTTP = nil): String; overload
function getRemoteXmlContent(const pUrl: string; http: TIdHTTP;var erro: string): String; overload
function getHTTPInstance: TidHTTP;
procedure downloadFile(url, filename: string);
implementation
function getHTTPInstance: TidHTTP;
var
http: TIdHTTP;
begin
http := TIdHTTP.Create(nil);
http.HandleRedirects := True;
http.ProtocolVersion := pv1_1;
http.HTTPOptions := http.HTTPOptions + [hoKeepOrigProtocol];
http.Request.Connection := 'keep-alive';
result := http;
end;
function getRemoteXmlContent(pUrl: string; http: TIdHTTP = nil): String;
var
criouHTTP: boolean;
begin
criouHttp := false;
if http = nil then
begin
criouHTTP := true;
http := getHTTPINstance;
end;
try
try
result := http.Get(pUrl);
except
result := '';
end;
finally
if criouHTTP and (http <> nil) then
FreeAndNil(http);
end;
end;
function getRemoteXmlContent(const pUrl: string; http: TIdHTTP;var erro: string): String;
var
criouHTTP: boolean;
retornoStream: TStringStream;
begin
criouHTTP := False;
Result := EmptyStr;
erro := EmptyStr;
retornoStream := TStringStream.Create('', TEncoding.UTF8);
try
if http = nil then
begin
criouHTTP := true;
http := getHTTPINstance;
end;
try
http.ConnectTimeout := 30000;
http.ReadTimeOut := 30000;
http.Get(pUrl, retornoStream);
except
on E: EIdHTTPProtocolException do
erro := E.ErrorMessage;
end;
Result := retornoStream.DataString;
finally
if criouHTTP and (http <> nil) then
FreeAndNil(http);
FreeAndNil(retornoStream);
end;
end;
procedure downloadFile(url, filename: string);
var
http: TIdHTTP;
ms: TMemoryStream;
begin
http := getHTTPInstance;
ms := TMemoryStream.Create;
try
http.Get(url, ms);
ms.SaveToFile(filename);
finally
FreeAndNil(http);
end;
end;
end.