forked from jamct/agsi-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1154_energy_api_agsi_plot14_64bit.txt
873 lines (778 loc) · 35.3 KB
/
1154_energy_api_agsi_plot14_64bit.txt
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
//****************API AGSI Iterate Tester**************************
program Rapid_API_AGSI_Get_Post1_plus14_64;
//https://www.techtarget.com/searchapparchitecture/definition/OpenAPI-Specification
//https://agsi.gie.eu/api
//https://rapidapi.com/maxkleiner1/api/maxbox4/tutorials
//based on json data on ct.de/y47m
//#TODO: right axis full [%] done - changed full from int2double
//https://github.com/maxkleiner/agsi-data for the BPM report
Const X_Rapidapi_Key = 'df61a35825msh66c95e953a7ap192bcfjsn16a_________';
SUserAgent = 'Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0) Gecko/25250101';
USERAGENTE = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0';
URLMALWARE ='http://malware.testing.google.test/testing/malware/';
//'http://chart.apis.google.com/chart?chs=%dx%d&cht=qr&chld=%s&chl=%s';
//Const /search?term=kiss%20the%20rain&locale=en-US&offset=0&limit=5 HTTP/1.1
procedure Form_CloseClick(Sender: TObject; var action: TCloseAction); forward;
Const PYHOME32 = 'C:\Users\max\AppData\Local\Programs\Python\Python36-32\';
procedure getURLScanAPI_Python(ftopic: string);
begin
with TPythonEngine.Create(Nil) do begin
pythonhome:= PYHOME32;
loadDLL();
try
Execstring('import urllib.request, json, requests');
ExecStr('headers={"Content-Type":"application/json"}')
ExecStr('data = {"url": "'+ftopic+'", "visibility": "public"}')
ExecStr('resp = requests.post("https://urlscan.io/api/v1/scan/",headers=headers, '+
'data=json.dumps(data))');
Print(EvalStr('resp'));
print(EvalStr('resp.json()'));
except
raiseError;
finally
//unloadDll;
Free;
end;
end;
end;
Const //please get your api key first: https://agsi.gie.eu/account
AGSI_APIKEY='16600670617ff72de59403f2a4bbb92f';
URL_AGSIAPI='https://agsi.gie.eu/api?country=%s&from=%s&size=%s&x-key:%s';
URL_AGSIAPI2='https://agsi.gie.eu/api?country=%s&from=%s&size=%s';
function GetEnergyStreamJSON(const Data, APIKEY: string): string;
var encodURL: string;
mapStrm: TStringStream;
jo: TJSONObject; asp: TStringArray;
begin
asp:= splitstr(data,',');
encodURL:= Format(URL_AGSIAPI2,[HTTPEncode(asp[0]),asp[1],asp[2],APIKEY]);
writeln(encodURL)
mapStrm:= TStringStream.create('');
try
HttpGet(EncodURL, mapStrm); //WinInet
mapStrm.Position:= 0;
jo:= TJSONObject.Create4(mapStrm.datastring);
writeln(jo.getstring('data'));
result:= jo.getjsonarray('data').getjsonobject(0).getstring('name');
result:= result+' '+jo.getjsonobject('full').getstring('full');
except
writeln('Error: '+mapstrm.datastring);
writeln('E: '+ExceptiontoString(exceptiontype, exceptionparam));
finally
mapStrm.Free;
encodURL:= '';
jo.Free;
end;
end;
// data plot functions--------------------------------------------------------//
var plotform: TForm;
procedure Form_CloseClick(Sender: TObject; var action: TCloseAction);
begin
//afrm.Close;
action:= cafree;
//chart1.Free;
writeln('EPlotform closed at: '+datetimetostr(now));
end;
//http://www.teechart.net/docs/teechart/vclfmx/lib/html/TBarSeries.html
function ChartInjector(aform: Tform): TChart;
var Ser1: TBarSeries; //TPieSeries, TFastLineSeries;
ser2, ser3: TLineSeries;
begin
result:= TChart.create(aform)
with result do begin
parent:= aform;
align:= alClient;
Title.Text.add('Sciplot: '+'GAS Injection / Full / Withdraw DE 2022 Ø');
LeftAxis.Title.Caption:= 'Injection GWh/d Amount';
RightAxis.Title.Caption:= 'Fulls in [%]';
Title.font.size:= 15;
//canvas
Ser1:= TBarSeries.create(result); // TPieSeries
ser1.parentchart:= result;
ser1.Marks.Visible := False
//serUllage.VertAxis := aRightAxis;
Legend.CheckBoxes:= True;
RightAxis.SetMinMax(0, 100);
LeftAxis.SetMinMax(0, 2000);
ser1.SeriesColor:= clGreen;
Ser1.ShowInLegend:= True;
ser1.title:= 'Injects'
Ser2:= TLineSeries.create(result);
ser2.VertAxis := aRightAxis;
//ser2.axis.automatic := 0;
ser2.parentchart:= result;
ser2.SeriesColor:= clRed;
ser2.title:= 'Full [%]'
Ser3:= TLineSeries.create(result);
//ser2.VertAxis := aRightAxis;
//ser2.axis.automatic := 0;
ser3.parentchart:= result;
ser3.SeriesColor:= clyellow;
ser3.title:= 'Wd.GWh'
//ser2.YValues.Multiplier:= 100;
View3D := False;
//Axes.Bottom.DateTimeFormat:= 'dd/mmm/yy';
//Free;
//muPixels muPercent
end;
//TFourPoints
//RectToFourPoints
end;
procedure JSON2Plot(form1: TForm; jar: TJSONArray);
var chart1: TChart;
cnt: integer; sumup,tmp2,tmp: double; gday: string;
begin
form1.onclose:= @Form_CloseClick;
chart1:= ChartInjector(form1);
sumup:=0; tmp2:=0; tmp:=0;
try
for cnt:= 0 to jar.length-1 do begin
//writeln(locate.getjsonobject(it).getstring('gasDayStart')+':'+
tmp:= jar.getjsonobject(jar.length-1-cnt).getdouble('injection');
tmp2:= jar.getjsonobject(jar.length-1-cnt).getdouble('full');
sumup:= sumup+tmp;
gday:= jar.getjsonobject(jar.length-1-cnt).getstring('gasDayStart');
chart1.Series[0].Addxy(cnt,tmp,gday,clgreen);
chart1.Series[1].Addxy(cnt,tmp2,'',clred);
chart1.Series[2].Addxy(cnt,jar.getjsonobject(jar.length-1-cnt).getdouble('withdrawal'),'',clyellow);
end;
except
writeln('EPlot: '+ExceptiontoString(exceptiontype, exceptionparam));
end;
PrintF(' Landrange %d: Injection sum: %.2f', [jar.length-1, sumup]);
end;
function letGenerateJSON2(HttpRqresponseText: string): TJSONArray;
var jo: TJSONObject;
begin
jo:= TJSONObject.Create4(HttpRqresponseText);
try
//writeln(jo.getstring('data'));
writeln(itoa(jo.getjsonarray('data').getjsonobject(0).length))
writeln(itoa(jo.getjsonarray('data').length))
result:= jo.getjsonarray('data');
//write out to check
for it:= 0 to result.length-1 do
writeln(result.getjsonobject(it).getstring('gasDayStart')+':'+
result.getjsonobject(it).getstring('injection'));
except
writeln('EJson: '+ExceptiontoString(exceptiontype, exceptionparam));
end;
end;
function getEnergyStreamJSON2(AURL, feedstream, aApikey: string): string;
var encodURL: string;
httpRq,hr: Olevariant;
asp: TStringArray;
begin
httpRq:= CreateOleObject('WinHttp.WinHttpRequest.5.1');
// Opens HTTPs connection.
try
asp:= splitStr(feedstream,',');
encodURL:= Format(AURL,[HTTPEncode(asp[0]),(asp[1]),asp[2]]);
writeln(encodurl)
hr:= httpRq.Open('GET', encodURL, false);
httpRq.setRequestheader('user-agent',USERAGENTE);
httpRq.setRequestheader('x-key',aAPIkey);
if hr= S_OK then HttpRq.Send();
If HttpRq.Status = 200 Then
result:= HttpRq.responseText
Else result:= 'Failed getting response:'+itoa(HttpRq.Status)+HttpRq.responseText;
//writeln('debug response: '+HttpReq.GetAllResponseHeaders);
except
writeln('Error: '+HttpRq.responseText);
writeln('EHTTP: '+ExceptiontoString(exceptiontype, exceptionparam));
finally
httprq:= unassigned;
end;
end;
//https://github.com/Zeus64/alcinoe/blob/master/source/ALHttpClient.pas
//http://www.softwareschule.ch/examples/alhttpclient2.txt
function TALHTTPClient_Get(aUrl: AnsiString;
feedstream, aApikey: string): string;
Var
LHttpClient: TALWininetHttpClient;
asp: TStringArray;
begin
LHttpClient:= TALWininetHttpClient.create;
asp:= splitStr(feedstream,',');
LHttpClient.url:= Format(AURL,[HTTPEncode(asp[0]),(asp[1]),asp[2]]);
LHttpClient.RequestMethod:= HTTPmt_Get; //HTTPrm_Post;
LHttpClient.RequestHeader.UserAgent:=USERAGENTE;
//LHttpClient.RequestHeader.CustomHeaders:=
LHttpClient.RequestHeader.RawHeaderText:='x-key:'+aAPIkey;
try
result:= LHttpClient.Get1(LHttpClient.url); //overload;
finally
LHttpClient.Free;
end;
end;
const
ESCAPE_CHAR = '\';
QUOTE_CHAR = '"';
EXCEPTION_FMT = 'Invalid escape at position %d';
function JSONUnescape(const Source: string; CRLF: string {= #13#10}): string;
var EscapeCharPos, TempPos: Integer;
Temp: string;
IsQuotedString: Boolean;
begin
if CRLF = '' then CRLF:= #13#10;
result:= '';
IsQuotedString:= (Source[1] = QUOTE_CHAR) and
(Source[Length(Source)] = QUOTE_CHAR);
EscapeCharPos:= Pos(ESCAPE_CHAR, Source);
TempPos:= 1;
while EscapeCharPos > 0 do begin
result:= result + Copy(Source, TempPos, EscapeCharPos - TempPos);
TempPos:= EscapeCharPos;
if EscapeCharPos < Length(Source) - booltoint(IsQuotedString) then
case Source[EscapeCharPos + 1] of
't':
Temp:= #9;
'n':
Temp:= CRLF;
'\':
Temp:= '\';
'"':
Temp:= '"';
'u':
begin
if EscapeCharPos + 4 < Length(Source) - Integer(IsQuotedString) then
Temp := Chr(StrToInt('$' + Copy(Source, EscapeCharPos + 2, 4)))
else begin
raise Exception.Create(Format(EXCEPTION_FMT, [EscapeCharPos]));
end;
Inc2(TempPos, 4);
end;
else begin
Xraise (Exception.Create(Format(EXCEPTION_FMT, [EscapeCharPos])));
end;
end
else begin
Xraise (Exception.Create(Format(EXCEPTION_FMT, [EscapeCharPos])));
end;
Inc2(TempPos, 2);
result:= result + Temp;
EscapeCharPos:= PosEx(ESCAPE_CHAR, Source, TempPos);
end;
result:= result + Copy(Source, TempPos, Length(Source) - TempPos + 1);
end;
var JTESTDATA: string;
procedure setTestData;
begin
JTESTDATA:=
'{ '+LF+
'"client": { '+LF+
' "clientId": "TestClient4", '+LF+
' "clientVersion": "1.1" '+LF+
'}, '+LF+
'"threatInfo": { '+LF+
' "threatTypes": ["MALWARE", "SOCIAL_ENGINEERING"],'+LF+
' "platformTypes": ["LINUX"], '+LF+
' "threatEntryTypes": ["URL"], '+LF+
' "threatEntries": [ '+LF+
' {"url": "%s"} '+LF+
' ] '+LF+
' } '+LF+
'}';
end;
{The ExecuteStr should include somewhere %1 because at this position the shell-order will be included. Example:
NAME: Chat;
Describtion: Chatprotocol;
ExecuteStr: "C:\ChatClient.exe %1".
Chat://2002/ -> executes: "C:\Chatclient.exe Chat://2002/"
}
procedure RegisterProtocol2(const Name, Describtion, ExecuteStr: string);
var reg: TRegistry;
begin
reg:= TRegistry.Create;
try
reg.RootKey:= HKEY_CLASSES_ROOT;
reg.OpenKey(Name, True);
try
reg.Writestring('', 'URL:' + Name +' (' + Describtion + ')');
reg.WriteInteger('EditFlags', 2);
reg.WriteString('Source Filter', '');
reg.WriteString('URL Protocol', '');
reg.OpenKey('shell', True);
reg.OpenKey('open', True);
reg.OpenKey('command', True);
reg.Writestring('', ExecuteStr);
finally
reg.CloseKey;
end;
finally
reg.Free;
end;
end;
function getPostGoogleAPI(feedstream, aApikey, tolang: string): string;
var
Url: string;
jo, locate: TJSONObject;
httpRq,hr: Olevariant;
strm: TStringStream;
begin
//setTestData before;
httpRq:= CreateOleObject('WinHttp.WinHttpRequest.5.1');
// Open HTTPs connection.
try
hr:= httpRq.Open('POST','https://safebrowsing.googleapis.com/v4/threatMatches:find?key='
+aApikey, false);
httpRq.setRequestheader('user-agent',SUSERAGENT );
httpRq.setRequestheader('content-type','application/json');
if hr= S_OK then HttpRq.Send(format(JTESTDATA,[feedstream]));
//writeln(format(JTESTDATA,[feedstream]));
If HttpRq.Status = 200 Then
result:= HttpRq.responseText
Else result:= 'Failed at getting response:'+itoa(HttpRq.Status)+HttpRq.responseText;
//writeln('debug response '+HttpReq.GetAllResponseHeaders);
finally
httprq:= unassigned;
end;
end;
var HttpResponse: string;
begin //@main
//maxform1.ShellStyle1click(self)
//maxform1.Console1Click(self)
//writeln(getMusicAPI_Com('kiss the rain' ,'en-US', 3));
//writeln(JSONUnescape('"\u2764Love\tAPI\u2764"', #13#10)); // {= #13#10})
//writeln(JSONUnescape('\\\Invalid escaped text',''));
//TALMultipartFormDataDecoder
//ALMultipartExtractBoundaryFromContentType - Gateway, Host, Adapter GHA
//ALBase64EncodeStringMIME
// ALHTTPdecode //TAlWinInetHTTPClientStatusEvent
//writeln(itoa(JExecute('cmd /C dir *.*',@TTextHandlerQ, true, false)));
//writeln(GETDOSOutput('cmd.exe /c wmic cpu get architecture','C:\'));
//writeln(itoa(JExecute('cmd /c netstat -o',@TTextHandlerQ, true, false)));
//Webbrowser1.Document.QueryInterface(IHTMLDocument2, iDoc);
//ExecuteScript(iDoc, 'document.login.submit()', 'JavaScript');
// writeln(getwapi) procedure GetDNSServers(AList: TStringList); GetDNSServers getIPs getips;
setTestData;
{ with TJson.create do begin
JTESTDATA:= format(JTESTDATA,['www.ibm.ch']);
parse(JTESTDATA);
writeln(Stringify);
clear;
free;
end; }
//writeln('GPost: '+getPostGoogleAPI('http://www.urltocheck1.org/',GoogleApiKey,''));
// writeln('GPost: '+getPostGoogleAPI(URLMALWARE, GoogleApiKey,''));
with TJson.create do begin
parse(JTESTDATA);
writeln(Stringify);
clear;
free;
end;
{ Note: If there are no matches (that is, if none of URLs specified in request are found on any of lists specified in a request), HTTP POST response simply returns empty object in response body. }
// writeln('GPost: '+getPostGoogleAPI('http://www.ibm.ch', GoogleApiKey,''));
// getURLScanAPI_Python('www.ibm.ch');
// writeln(GetEnergyStreamJSON('DE,2022-03-01,20',AGSI_APIKEY));
plotform:= getForm2(1400, 600, clsilver, 'Sciplot4maXbox');
plotform.icon.loadfromresourcename(hinstance,'ZHISTOGRAM');
HttpResponse:= getEnergyStreamJSON2(URL_AGSIAPI2,'DE,2023-01-03,150',AGSI_APIKEY);
//HttpResponse:= getEnergyStreamJSON('DE,2023-01-03,150',AGSI_APIKEY);
JSON2Plot(plotform, letGenerateJSON2(HttpResponse));
//writeln(TALHTTPClient_Get(URL_AGSIAPI2,'DE,2022-01-03,10',AGSI_APIKEY));
//LOCALE_US LOCALE_PORTUGUESE_BRAZILIAN MediaType_Xml MediaType_Json
//TStatusCode TRestUtils TStatusCode TReponseCode
//GetNetworkConnections: string; //GetNetworkDrives
//timesync letSynchroTime
//ParseString4(s,sep: string; sl: TStrings);
//LoadGridFromfile(SG: TStringGrid; fname: string);
//SaveGridTofile(SG: TStringGrid; fname: string);
//WriteVectorToGrid(SG: TStringGrid; vname: string; wval: TAffineVector);
//WriteStringToGrid(SG: TStringGrid; vname: string; icol: longword; wval: string);
//WriteFloatToGrid(SG: TStringGrid; vname: string; icol: longword; wval: double);
//writeln(GETDOSOutput('cmd.exe /c netstat -o','C:\'));
End.
Ref history:
[]
Error: {"last_page":0,"total":0,"dataset":"storage ERROR","error":"access denied","message":"Invalid or missing API key","data":[]}
E: Exception: TJSONArray[0] not found.
get a api key first: https://agsi.gie.eu/account
GitGuardian has detected the following Google API Key exposed within your GitHub account.
Exception: WinHttp.WinHttpRequest: The data necessary to complete this operation is not yet available.
The data represents gas in storage at the end of the previous gas day. Data is updated every day at 19:30 CET and a second time at 23:00. GIE is providing an API (Application Programming Interface) service on its AGSI and ALSI transparency publication platforms.
Using API access, the audience can bypass the AGSI and ALSI website and get hold of the data directly and continuously. It enables to extract, filter the data and create any subset as required, without having to download each dataset separately from the website. The API export format is JSON.
Details
- Secret type: Google API Key
- Repository: maxkleiner/agsi-data
- Pushed date: September 16th 2022, 13:58:37 UTC
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(theUrl);
request.addHeader("x-api-key", apiKey);
HttpResponse response = httpclient.execute(request);
https://stackoverflow.com/questions/5334997/rest-get-requests-verbs-and-apikey
Doc: https://rapidapi.com/collection/list-of-free-apis
https://algosim.org/SynViewSource/
https://stackoverflow.com/questions/37410849/safe-browsing-lookup-api-v4-invalid-json-payload-received
log doc:
GPost: Failed at getting response:403{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"status": "PERMISSION_DENIED"
}
}
GPost: Failed at getting response:400{
"error": {
"code": 400,
"message": "API key not valid. Please pass a valid API key.",
"status": "INVALID_ARGUMENT",
"details": [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "API_KEY_INVALID",
"domain": "googleapis.com",
"metadata": {
"service": "safebrowsing.googleapis.com"
}
}
]
}
}
GPost: Failed at getting response:403{
"error": {
"code": 403,
"message": "Safe Browsing API has not been used in project 338972382324 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/safebrowsing.googleapis.com/overview?project=338972382324 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
"status": "PERMISSION_DENIED",
"details": [
{
"@type": "type.googleapis.com/google.rpc.Help",
"links": [
{
"description": "Google developers console API activation",
"url": "https://console.developers.google.com/apis/api/safebrowsing.googleapis.com/overview?project=338972382324"
}
]
},
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "SERVICE_DISABLED",
"domain": "googleapis.com",
"metadata": {
"service": "safebrowsing.googleapis.com",
"consumer": "projects/338972382324"
}
}
]
}
}
https://stackoverflow.com/questions/5661596/do-i-need-a-content-type-header-for-http-get-requests
As far as I understood there are two places where to set the content type:
The client sets a content type for the body he is sending to the server (e.g. for post)
The server sets a content type for the response.
A sender that generates a message containing a payload body SHOULD generate a Content-Type header field in that message unless the intended media type of the enclosed representation is unknown to the sender. If a Content-Type header field is not present, the recipient MAY either assume a media type of "application/octet-stream" ([RFC2046], Section 4.5.1) or examine the data to determine its type.
It means that the Content-Type HTTP header should be set only for PUT and POST requests.
GET requests can have "Accept" headers, which say which types of content the client understands. The server can then use that to decide which content type to send back.
writeln(GETDOSOutput('cmd.exe /c wmic cpu get architecture','C:\'));
writeln(GETDOSOutput('cmd.exe /c wmic cpu get name','C:\'));
//to monitor tcp spyware over PID - process ID
memo2.setFocus;
repeat
writeln(GETDOSOutput('cmd.exe /c netstat -o','C:\'));
memo2.color:= clsilver;
sleep(2000)
memo2.color:= clyellow;
until isKeyPressed;
memo2.color:= clwhite;
writeln(SysErrorMessage(GetLastError))
Doc: TALWininetHttpClient
TALWinInetHttpClient is a is easy to use WinInet-based. HTTP client component which allows to post and get. any data from the Web via HTTP protocol.
https://svn.code.sf.net/p/alcinoe/code/demos/ALWinInetHTTPClient/_source/Unit1.pas
https://docwiki.embarcadero.com/Libraries/Sydney/en/System.Net.HttpClient.THTTPClient.Post
https://stackoverflow.com/questions/9713491/delphi-decode-json-utf8-escaped-text
12
\uXXXX is the JSON Unicode escape notation (X is hexadecimal).
ref:
--------------------------------------------------------
TWinApiDownload = class(TObject)
private
fEventWorkStart : TEventWorkStart;
fEventWork : TEventWork;
fEventWorkEnd : TEventWorkEnd;
fEventError : TEventError;
fURL : string;
fUserAgent : string;
fStop : Boolean;
fActive : Boolean;
fCachingEnabled : Boolean;
fProgressUpdateInterval : Cardinal;
function GetIsActive : Boolean;
public
constructor Create;
destructor Destroy; override;
function CheckURL(aURL: string) : Integer;
function Download(Stream : TStream) : Integer; overload;
function Download(var res : string) : Integer; overload;
function ErrorCodeToMessageString(aErrorCode : Integer) : string;
procedure Stop;
procedure Clear;
property UserAgent : string read fUserAgent write fUserAgent;
property URL : string read fURL write fURL;
property DownloadActive : Boolean read GetIsActive;
property CachingEnabled : Boolean read fCachingEnabled write fCachingEnabled;
property UpdateInterval:Cardinal read fProgressUpdateInterval write fProgressUpdateInterval;
property OnWorkStart : TEventWorkStart read fEventWorkStart write fEventWorkStart;
property OnWork : TEventWork read fEventWork write fEventWork;
property OnWorkEnd : TEventWorkEnd read fEventWorkEnd write fEventWorkEnd;
property OnError : TEventError read fEventError write fEventError;
end;
procedure SIRegister_TJSONObject(CL: TPSPascalCompiler);
begin
//with RegClassS(CL,'TZAbstractObject', 'TJSONObject') do
with CL.AddClassN(CL.FindClass('TZAbstractObject'),'TJSONObject') do
begin
RegisterMethod('Constructor create;');
RegisterMethod('Constructor create1( jo : TJSONObject; sa : array of string);');
RegisterMethod('Constructor create2( x : JSONTokener);');
RegisterMethod('Constructor create3( map : TStringList);');
RegisterMethod('Constructor create4( s : string);');
RegisterMethod('Procedure clean');
Function clone : TZAbstractObject');
Function accumulate( key : string; value : TZAbstractObject) : TJSONObject');
Function get( key : string) : TZAbstractObject');
Function getBoolean( key : string) : boolean');
Function getDouble( key : string) : double');
Function getInt( key : string) : integer');
Function getJSONArray( key : string) : TJSONArray');
Function getJSONObject( key : string) : TJSONObject');
Function getString( key : string) : string');
Function has( key : string) : boolean');
Function isNull( key : string) : boolean');
Function keys : TStringList');
Function length : integer');
Function names : TJSONArray');
Function numberToString( n : _Number) : string');
Function valueToString( value : TZAbstractObject) : string;');
Function valueToString1( value : TZAbstractObject; indentFactor, indent : integer) : string;');
Function opt( key : string) : TZAbstractObject');
Function optBoolean( key : string) : boolean;');
Function optBoolean1( key : string; defaultValue : boolean) : boolean;');
Function optDouble( key : string) : double;');
Function optDouble1( key : string; defaultValue : double) : double;');
Function optInt( key : string) : integer;');
Function optInt1( key : string; defaultValue : integer) : integer;');
Function optString( key : string) : string;');
Function optString1( key : string; defaultValue : string) : string;');
Function optJSONArray( key : string) : TJSONArray;');
Function optJSONObject( key : string) : TJSONObject;');
Function put( key : string; value : boolean) : TJSONObject;');
Function put1( key : string; value : double) : TJSONObject;');
Function put2( key : string; value : integer) : TJSONObject;');
Function put3( key : string; value : string) : TJSONObject;');
Function put4( key : string; value : TZAbstractObject) : TJSONObject;');
Function putOpt( key : string; value : TZAbstractObject) : TJSONObject');
Function quote( s : string) : string');
Function remove( key : string) : TZAbstractObject');
Procedure assignTo( json : TJSONObject)');
Function toJSONArray( names : TJSONArray) : TJSONArray');
Function toString1( indentFactor : integer) : string;');
Function toString2( indentFactor, indent : integer) : string;');
RegisterMethod('Function NULL : NULL');
end;
end;
E: Exception: Access violation at address 01F0CC04 in module 'maXbox4.exe'. Read of address 00000000.
Failed at getting response:415HTTP 415 Unsupported Media Type
Failed at getting response: 503503 - Service Unavailable
C:\maXbox\works2021\maxbox4>py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import http.client
>>>
>>> conn = http.client.HTTPSConnection("nlp-translation.p.rapidapi.com")
>>> payload = "text=Hello%20World&to=es&from=en"
>>> headers = {
... 'content-type': "application/x-www-form-urlencoded",
... 'X-RapidAPI-Host': "nlp-translation.p.rapidapi.com",
... 'X-RapidAPI-Key': "df61a35825msh66c9514de953a7ap192bcfjsn16a3d1018ce3"
... }
>>> conn.request("POST", "/v1/translate", payload, headers)
>>>
>>> res = conn.getresponse()
>>> data = res.read()
>>> print(data.decode("utf-8"))
{"message":"You are not subscribed to this API."}
>>> Failed at getting response: 503503 - Service Unavailable
Passwort checker? https://haveibeenpwned.com
https://dnslytics.com/spf-lookup
procedure RunDosInMemo(DosApp: string; AMemo:TMemo);
const
READ_BUFFER_SIZE = 2400;
var
Security: TSecurityAttributes;
readableEndOfPipe, writeableEndOfPipe: THandle;
start: TStartUpInfo;
ProcessInfo: TProcessInformation;
Buffer: PAnsiChar;
BytesRead: DWORD;
AppRunning: DWORD;
begin
Security.nLength := SizeOf(TSecurityAttributes);
Security.bInheritHandle := True;
Security.lpSecurityDescriptor := nil;
if CreatePipe({var}readableEndOfPipe, {var}writeableEndOfPipe, @Security, 0) then
begin
Buffer := AllocMem(READ_BUFFER_SIZE+1);
FillChar(Start, Sizeof(Start), #0);
start.cb := SizeOf(start);
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
// - Redirect the output and error to the writeable end of our pipe.
// - We must still supply a valid StdInput handle (because we used STARTF_USESTDHANDLES to swear that all three handles will be valid)
start.dwFlags := start.dwFlags or STARTF_USESTDHANDLES;
start.hStdInput := GetStdHandle(STD_INPUT_HANDLE); //we're not redirecting stdInput; but we still have to give it a valid handle
start.hStdOutput := writeableEndOfPipe; //we give the writeable end of the pipe to the child process; we read from the readable end
start.hStdError := writeableEndOfPipe;
//We can also choose to say that the wShowWindow member contains a value.
//In our case we want to force the console window to be hidden.
start.dwFlags := start.dwFlags + STARTF_USESHOWWINDOW;
start.wShowWindow := SW_HIDE;
// Don't forget to set up members of the PROCESS_INFORMATION structure.
ProcessInfo := Default(TProcessInformation);
//WARNING: The unicode version of CreateProcess (CreateProcessW) can modify the command-line "DosApp" string.
//Therefore "DosApp" cannot be a pointer to read-only memory, or an ACCESS_VIOLATION will occur.
//We can ensure it's not read-only with the RTL function: UniqueString
UniqueString({var}DosApp);
if CreateProcess(nil, PChar(DosApp), nil, nil, True, NORMAL_PRIORITY_CLASS, nil, nil, start, {var}ProcessInfo) then
begin
//Wait for the application to terminate, as it writes it's output to the pipe.
//WARNING: If the console app outputs more than 2400 bytes (ReadBuffer),
//it will block on writing to the pipe and *never* close.
repeat
Apprunning := WaitForSingleObject(ProcessInfo.hProcess, 100);
Application.ProcessMessages;
until (Apprunning <> WAIT_TIMEOUT);
//Read the contents of the pipe out of the readable end
//WARNING: if the console app never writes anything to the StdOutput, then ReadFile will block and never return
repeat
BytesRead := 0;
ReadFile(readableEndOfPipe, Buffer[0], READ_BUFFER_SIZE, {var}BytesRead, nil);
Buffer[BytesRead]:= #0;
OemToAnsi(Buffer,Buffer);
AMemo.Text := AMemo.text + String(Buffer);
until (BytesRead < READ_BUFFER_SIZE);
end;
FreeMem(Buffer);
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
CloseHandle(readableEndOfPipe);
CloseHandle(writeableEndOfPipe);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin {button 1 code}
RunDosInMemo('chkdsk.exe c:\',Memo1);
end;
CL.AddDelphiFunction('procedure RunDosInMemo(DosApp: string; AMemo:TMemo);');
ShellExecute(0, 'open', Pchar('DocumentName.pdf'), '', '', SW_SHOWNORMAL);
work under Windows 7 and 8, which would start the Acrobat Reader and open the file but under Windows 10 this no longer is the case. So the next step was to update the call to use ShellExecuteEX instead.
ShellInfo := Default(TShellExecuteInfo);
ShellInfo.cbSize := SizeOf(TShellExecuteInfo);
ShellInfo.lpFile := PChar(Current_Client_Documents + FileName +'.pdf');
ShellInfo.nShow := SW_SHOWNORMAL;
try
ShellExecuteEx(@ShellInfo);
The actual code will prepare the Object ShellInfo to contain all of the necessary data to start up the Acrobat Reader and display the generated PDF.
//make a GET request using the WinInet functions
function Https_Get(const ServerName,Resource : string;Var Response:AnsiString): Integer;
const
BufferSize=1024*64;
var
hInet : HINTERNET;
hConnect : HINTERNET;
hRequest : HINTERNET;
ErrorCode : Integer;
lpvBuffer : PAnsiChar;
lpdwBufferLength: DWORD;
lpdwReserved : DWORD;
dwBytesRead : DWORD;
lpdwNumberOfBytesAvailable: DWORD;
begin
Result :=0;
Response:='';
hInet := InternetOpen(PChar(sUserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if hInet=nil then begin
ErrorCode:=GetLastError;
raise Exception.Create(Format('InternetOpen Error %d Description %s',
[ErrorCode,GetWinInetError(ErrorCode)]));
end;
try
hConnect := InternetConnect(hInet, PChar(ServerName), INTERNET_DEFAULT_HTTPS_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 0);
if hConnect=nil then begin
ErrorCode:=GetLastError;
raise Exception.Create(Format('InternetConnect Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
end;
try
//make the request
hRequest := HttpOpenRequest(hConnect, 'GET', PChar(Resource), HTTP_VERSION, '', nil, INTERNET_FLAG_SECURE, 0);
if hRequest=nil then begin
ErrorCode:=GetLastError;
raise Exception.Create(Format('HttpOpenRequest Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
end;
try
//send the GET request
if not HttpSendRequest(hRequest, nil, 0, nil, 0) then begin
ErrorCode:=GetLastError;
raise Exception.Create(Format('HttpSendRequest Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
end;
lpdwBufferLength:=SizeOf(Result);
lpdwReserved :=0;
//get the status code
if not HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER, @Result, lpdwBufferLength, lpdwReserved) then begin
ErrorCode:=GetLastError;
raise Exception.Create(Format('HttpQueryInfo Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
end;
if Result=200 then //read the body response in case which the status code is 200
if InternetQueryDataAvailable(hRequest, lpdwNumberOfBytesAvailable, 0, 0) then begin
GetMem(lpvBuffer,lpdwBufferLength);
try
SetLength(Response,lpdwNumberOfBytesAvailable);
InternetReadFile(hRequest, @Response[1], lpdwNumberOfBytesAvailable, dwBytesRead);
finally
FreeMem(lpvBuffer);
end;
end
else begin
ErrorCode:=GetLastError;
raise Exception.Create(Format('InternetQueryDataAvailable Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
end;
finally
InternetCloseHandle(hRequest);
end;
finally
InternetCloseHandle(hConnect);
end;
finally
InternetCloseHandle(hInet);
end;
end;
RegisterPublishedProperties;
RegisterProperty('Brush', 'TChartBrush', iptrw);
RegisterProperty('Pen', 'TChartPen', iptrw);
RegisterProperty('Font', 'TTeeFont', iptrw);
RegisterProperty('Color', 'TColor', iptrw);
//RegisterProperty('Handle', 'TTeeCanvasHandle', iptr);
RegisterProperty('Gradient', 'TTeeGradient', iptrw);
RegisterProperty('Picture', 'TBackimage', iptrw);
RegisterProperty('Shadow', 'TTEEShadow', iptrw);
RegisterProperty('ShypeStyle', 'TChartObjectShapeStyle', iptrw);
RegisterProperty('Style', 'TPenStyle', iptrw);
RegisterProperty('Frame', 'TChartPen', iptrw);
RegisterProperty('Transparent', 'boolean', iptrw);
RegisterProperty('Tranparency', 'integer', iptrw);
RegisterProperty('Visible', 'boolean', iptrw);
RegisterMethod(@TCustomAxisPanel.Destroy, 'Free');
RegisterMethod(@TCustomAxisPanel.Assign, 'Assign');
RegisterMethod('Procedure Assign( Source : TPersistent)');
RegisterMethod('Procedure Free;');
mX4 executed: 29/08/2022 11:15:20 Runtime: 0:0:1.952 Memload: 42% use
mX4 executed: 29/08/2022 11:15:33 Runtime: 0:0:1.803 Memload: 42% use
mX4 executed: 29/08/2022 11:21:34 Runtime: 0:0:1.771 Memload: 42% use
mX4 executed: 30/08/2022 14:01:29 Runtime: 0:0:2.477 Memload: 45% use
mX4 executed: 30/08/2022 15:43:22 Runtime: 0:0:2.406 Memload: 45% use
mX4 executed: 30/08/2022 16:07:02 Runtime: 0:0:2.369 Memload: 45% use
mX4 executed: 15/09/2022 09:48:03 Runtime: 0:0:2.790 Memload: 37% use
mX4 executed: 15/09/2022 22:28:52 Runtime: 0:0:7.33 Memload: 41% use
mX4 executed: 16/09/2022 14:03:40 Runtime: 0:0:7.696 Memload: 43% use
mX4 executed: 10/10/2022 16:28:42 Runtime: 0:0:7.178 Memload: 43% use
mX4 executed: 10/10/2022 16:39:37 Runtime: 0:0:11.703 Memload: 44% use