-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapirequest.pas
More file actions
429 lines (357 loc) · 11.9 KB
/
apirequest.pas
File metadata and controls
429 lines (357 loc) · 11.9 KB
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
unit ApiRequest;
//https://wiki.freepascal.org/fcl-json
{$mode ObjFPC}{$H+}
interface
uses
Classes, SysUtils, Forms, fphttpclient, ComCtrls, fpjson, StrUtils, StdCtrls,
appdbFQ;
type
{ TApiRequest }
TApiRequest = class(TObject)
private
function JsonSearchPath(aText : String) : String;
public
ApiRequestData : array of ApiObjectData;
FieldNames : array of String;
Trv: TTreeView;
constructor Create; overload;
destructor Destroy; override;
function ReadURLGet : string; // Get request
function ReadURLPost : string; // Post request
procedure ShowJSONData(AParent : TTreeNode; Data : TJSONData);
procedure ExpandTreeNodes(Nodes: TTreeNodes; Level: Integer);
function FormatJsonData(json : TJSONData) : String;
procedure GetJsonData(aTrv : TTreeView; StatusBar : TStatusBar; aMemo : TMemo);
procedure GetJsonTextFile(aTrv : TTreeView; StatusBar : TStatusBar; SourceMemo, DestMemo : TMemo);
function GetExternalIPAddress: string;
end;
Resourcestring
SCaption = 'JSON Viewer';
SEmpty = 'Empty document';
SArray = 'Array (%d elements)';
SObject = 'Object (%d members)';
SNull = 'null';
implementation
uses Form_Main, RegExpr {extrernalIPadress};
{ TApiRequest }
constructor TApiRequest.Create();
begin
inherited;
SetLength(ApiRequestData, 1);
SetLength(FieldNames, 0);
//...
end;
destructor TApiRequest.Destroy;
begin
//...
inherited Destroy;
end;
function TApiRequest.ReadURLGet: string;
var
Client: TFPHttpClient;
respons : String;
Params : string;
begin
Client := TFPHttpClient.Create(nil);
with Client do
try
if ApiRequestData[0].Authentication then begin
UserName := ApiRequestData[0].AuthenticationUserName;
Password := ApiRequestData[0].AuthenticationPassword;
end;
// Search if the URL needs a Token => [Token]
if pos('[Token]', ApiRequestData[0].Url) > 0 then begin
ApiRequestData[0].Url := StringReplace(ApiRequestData[0].Url, '[Token]', ApiRequestData[0].Token, [rfIgnoreCase]);
end
else if pos('[token]', ApiRequestData[0].Url {Url}) > 0 then begin
ApiRequestData[0].Url := StringReplace(ApiRequestData[0].Url, '[token]', ApiRequestData[0].Token, [rfIgnoreCase]);
end;
if ApiRequestData[0].Authentication then begin
UserName := ApiRequestData[0].AuthenticationUserName;
Password := ApiRequestData[0].AuthenticationPassword;
respons:= Get(ApiRequestData[0].Url);
end
else begin
respons:= Get(ApiRequestData[0].Url);
end;
finally
RequestBody.Free;
Client.Free;
end;
result := respons;
end;
function TApiRequest.ReadURLPost: string;
var
Client: TFPHttpClient;
respons : String;
Params : string;
begin
Client := TFPHttpClient.Create(nil);
with Client do
try
if ApiRequestData[0].Authentication then begin
UserName := ApiRequestData[0].AuthenticationUserName;
Password := ApiRequestData[0].AuthenticationPassword;
end;
// Search if the URL needs a Token => [Token]
if pos('[Token]', ApiRequestData[0].Url) > 0 then begin
ApiRequestData[0].Url := StringReplace(ApiRequestData[0].Url, '[Token]', ApiRequestData[0].Token, [rfIgnoreCase]);
end
else if pos('[token]', ApiRequestData[0].Url {Url}) > 0 then begin
ApiRequestData[0].Url := StringReplace(ApiRequestData[0].Url, '[token]', ApiRequestData[0].Token, [rfIgnoreCase]);
end;
AddHeader('Content-Type','application/json; charset=UTF-8');
AddHeader('Accept', 'application/json');
AllowRedirect := true;
Params := ApiRequestData[0].Request_body;
RequestBody := TRawByteStringStream.Create(Params);
respons := Post(ApiRequestData[0].Url);
finally
RequestBody.Free;
Client.Free;
end;
result := respons;
end;
procedure TApiRequest.ShowJSONData(AParent: TTreeNode; Data: TJSONData);
// source: ...:\lazarus\tools\jsonviewer\*.*
var
Node_1 , Node_2 : TTreeNode;
I : Integer;
JsonData : TJSONData;
aString : String;
Strlist : TStringList;
begin
// Counter := 1;
if AParent <> Nil then
Node_1 := AParent
else
Node_1 := Trv.Items.AddChild(AParent,'');
Case Data.JSONType of
jtArray, jtObject:
begin
If (Data.JSONType=jtArray) then
aString := SArray
else
aString := SObject;
aString := Format(aString,[Data.Count]); // format the string, add number of objects
Strlist := TstringList.Create;
try
For I := 0 to Data.Count - 1 do
If Data.JSONtype = jtArray then begin
Strlist.AddObject(IntToStr(I),Data.items[i]);
end
else begin
Strlist.AddObject(TJSONObject(Data).Names[i],Data.items[i]);
FrmMain.Logging.WriteToLogAndFlushDebug(Strlist[i] + ': '); // Write field names mowet naar een tstringlist
SetLength(FieldNames, Length(FieldNames)+1);
FieldNames[Length(FieldNames)-1] := Strlist[i];
end;
//S.Sort;
For I := 0 to Strlist.Count - 1 do begin
Node_2 := Trv.Items.AddChild(Node_1 , Strlist[i]);
JsonData := TJSONData(Strlist.Objects[i]);
//Node_2.ImageIndex := ImageTypeMap[JsonData.JSONType];
//Node_2.SelectedIndex := ImageTypeMap[JsonData.JSONType];
ShowJSONData(Node_2 , JsonData);
if Strlist.Objects[i].ToString = 'TJSONString' then begin
FrmMain.Logging.WriteToLogAndFlushDebug(Strlist[i]);
SetLength(FieldNames, Length(FieldNames)+1);
FieldNames[Length(FieldNames)-1] := Strlist[i];
end;
end
finally
Strlist.Free;
end;
end;
jtNull:
aString := SNull;
else
aString := Data.AsString;
// if Options.FQuoteStrings and (Data.JSONType=jtString) then
aString := '"' + aString + '"';
end; // end case
If Assigned(Node_1) then begin
If Node_1.Text = '' then
Node_1.Text := aString
else
Node_1.Text := Node_1.Text+': '+ aString;
//Node_1.ImageIndex := ImageTypeMap[Data.JSONType];
//Node_1.SelectedIndex := ImageTypeMap[Data.JSONType];
end;
end;
procedure TApiRequest.ExpandTreeNodes(Nodes: TTreeNodes; Level: Integer);
var
I: Integer;
begin
Nodes.BeginUpdate;
try
for I := 0 to Nodes.Count - 1 do
if Nodes[I].Level < Level then
Nodes[I].Expand(False);
finally
Nodes.EndUpdate;
end;
end;
function TApiRequest.FormatJsonData(json: TJSONData): String;
var
s : String;
begin
s := json.FormatJSON;
result := s; //json.FormatJSON; // "pretty print"
end;
function TApiRequest.JsonSearchPath(aText: String): String;
var
A: TStringArray;
i : Integer;
begin
if aText <> '' then begin
A := aText.Split('[,]');
for i:=0 to Length(A)-1 do begin
if A[i] <> '' then begin
if JsonSearchpath = '' then
JsonSearchpath := A[i]
else
JsonSearchpath += '.' + A[i]
end;
end;
end;
result := JsonSearchpath;
end;
procedure TApiRequest.GetJsonData(aTrv: TTreeView; StatusBar : TStatusBar; aMemo : TMemo);
var
JsonText, PagingSearchText, RequestUrlExecute : string;
jData : TJSONData;
Node: TTreeNode;
i : Integer;
PagesTotal : Integer;
_StatusBar : TStatusBar;
x : Integer;
begin
if StatusBar is TStatusBar then begin
_StatusBar := TStatusBar(StatusBar);
end;
PagesTotal := 0;
if ( ApiRequestData[0].ObjectType = appdbFQ.Query) and (ApiRequestData[0].Url <> '') then begin
_StatusBar.Panels.Items[0].Text := ' Testen API request "' + ApiRequestData[0].Url + '"...';
Application.ProcessMessages;
aMemo.Clear;
aTrv.BeginUpdate;
try
if ApiRequestData[0].HTTP_Methode = 'Get' then
JsonText := ReadURLGet
else
JsonText := ReadURLPost;
jData := GetJSON(JsonText);
PagingSearchText := JsonSearchPath(ApiRequestData[0].Paging_searchtext); // Create search path. Search for a specific text in the json which gives the amount of pages.
if PagingSearchText <> '' then begin
if jData.FindPath(PagingSearchText) <> nil then begin
PagesTotal := JData.GetPath(PagingSearchText).AsInteger;
end
else begin
PagesTotal := jData.GetPath(PagingSearchText).AsInteger;
end;
end;
aTrv.Items.Clear;
aTrv.Items.Add (nil,'Root Node');
Node := aTrv.Items[0];
Trv := aTrv;
// go through all the pages
if PagesTotal > 1 then begin
jData.Free;
ApiRequestData[0].Url += '?page='; // =======>>>>>>> Let op!, dit is misschien anders bij andere API's. In de gaten houden.
for i := 1 to PagesTotal do begin
RequestUrlExecute := ApiRequestData[0].Url + IntToStr(i);
_StatusBar.Panels.Items[0].Text := 'Testen API request "' + RequestUrlExecute + '"...';
Application.ProcessMessages;
if ApiRequestData[0].HTTP_Methode = 'Get' then
JsonText := ReadURLGet
else
JsonText := ReadURLPost;
jData := GetJSON(JsonText);
ShowJSONData(Node,jData);
aMemo.Lines.Add(FormatJsonData(jData));
jData.Free;
end;
end
else begin
ShowJSONData(Node,jData);
aMemo.Lines.Add(FormatJsonData(jData));
jData.Free;
end;
finally
ExpandTreeNodes(aTrv.Items, 2); // Expand the first level of the treeview
aTrv.EndUpdate;
_StatusBar.Panels.Items[0].Text := '';
Application.ProcessMessages;
end;
end
else begin
FrmMain.Logging.WriteToLogInfo('Betreft géén query maar een folder. Kan geen https request uitvoeren vanuit een folder.');
end;
end;
procedure TApiRequest.GetJsonTextFile(aTrv: TTreeView; StatusBar: TStatusBar; SourceMemo, DestMemo: TMemo);
var
JsonText : string;
jData : TJSONData;
Node: TTreeNode;
_StatusBar : TStatusBar;
begin
if StatusBar is TStatusBar then begin
_StatusBar := TStatusBar(StatusBar);
end;
_StatusBar.Panels.Items[0].Text := 'Bezig met het openen en formateren van de Jsonfile...';
Application.ProcessMessages;
DestMemo.Clear;
aTrv.BeginUpdate;
try
JsonText := SourceMemo.Text;
jData := GetJSON(JsonText);
aTrv.Items.Clear;
aTrv.Items.Add (nil,'Root Node');
Node := aTrv.Items[0];
Trv := aTrv;
ShowJSONData(Node,jData);
DestMemo.Lines.Add(FormatJsonData(jData));
jData.Free;
finally
ExpandTreeNodes(aTrv.Items, 2); // Expand the first level of the treeview
aTrv.EndUpdate;
_StatusBar.Panels.Items[0].Text := '';
Application.ProcessMessages;
end;
end;
function TApiRequest.GetExternalIPAddress: string;
var
HTTPClient: TFPHTTPClient;
IPRegex: TRegExpr;
RawData: string;
begin
try
HTTPClient := TFPHTTPClient.Create(nil);
IPRegex := TRegExpr.Create;
try
//returns something like:
{
<html><head><title>Current IP Check</title></head><body>Current IP Address: 44.151.191.44</body></html>
}
RawData := HTTPClient.Get('http://checkip.dyndns.org');
// adjust for expected output; we just capture the first IP address now:
IPRegex.Expression := '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b';
//or '\b(?:\d{1,3}\.){3}\d{1,3}\b'
if IPRegex.Exec(RawData) then
Result := IPRegex.Match[0]
else
Result := 'Got invalid results getting external IP address. Details:'
+ LineEnding + RawData;
except
on E: Exception do
begin
Result := 'Error retrieving external IP address: ' + E.Message;
end;
end;
finally
HTTPClient.Free;
IPRegex.Free;
end;
end;
end.