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
|
procedure TFrmMain.Button1Click(Sender: TObject);
procedure GetInternetFile(const AServerName: string; const AURL: string; AStream: TStream; const ExpectedContentType: string = '');
type
TAcceptTypes = packed array[0..1] of LPWSTR;
const
BufferSize = 1024;
ACCEPT_TYPES: TAcceptTypes = (PChar('text/*'), nil); // PCTSTR rgpszAcceptTypes[] = {_T(text/*), NULL};
var
hSession, hHTTP, hReq : HINTERNET;
Accept: TAcceptTypes;
Buffer: array[1..BufferSize] of Byte;
BufferLen: DWORD;
sAppName: string;
begin
AStream.Size := 0;
sAppName := ExtractFileName(Application.ExeName);
Accept := ACCEPT_TYPES;
if ExpectedContentType <> '' then
Accept[0] := PChar(ExpectedContentType);
// Winapi.WinInet !!!
hSession := InternetOpen(PChar(sAppName), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
try
hHTTP := InternetConnect(hSession, PChar(AServerName), INTERNET_DEFAULT_HTTP_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 1);
try
hReq := HttpOpenRequest(hHTTP, PChar('GET'), PChar(AURL), nil, nil, @accept, 0, 1);
try
if HttpSendRequest(hReq, nil, 0, nil, 0) then
begin
BufferLen := 0;
repeat
if InternetReadFile(hReq, @Buffer, BufferSize, BufferLen) then
AStream.WriteBuffer(Buffer, BufferLen);
until BufferLen = 0;
end
else
raise Exception.Create('HttpOpenRequest failed. ' + SysErrorMessage(GetLastError));
finally
InternetCloseHandle(hReq);
end;
finally
InternetCloseHandle(hHTTP);
end;
finally
InternetCloseHandle(hSession);
end;
end;
var
JSONStream: TStringStream;
ResponseJSON: TJSONObject;
Pair: TJSONPair;
begin
JSONStream := TStringStream.Create('', TEncoding.UTF8);
try
GetInternetFile('calendrier.api.gouv.fr', '/jours-feries/metropole.json', JSONStream, 'application/json');
ResponseJSON := TJSONObject.ParseJSONValue(JSONStream.DataString) as TJSONObject; // UTF8 !
try
for Pair in ResponseJSON do
ValueListEditor1.Values[Pair.JsonString.Value] := Pair.JsonValue.Value;
finally
ResponseJSON.Free();
end;
finally
JSONStream.Free();
end;
end; |
Partager