How to use TIdHTTP to get json dynamically in code with Delphi?

204 views Asked by At

When I do a GET request to "https://api.github.com/users/octocat" in Postman, then it works:

Postman GET

But If I try to do it in Delphi using TIdHTTP using the following code:

procedure TForm1.Button1Click(Sender: TObject);
begin
  var apiURL := 'https://api.github.com/users/octocat';
  try
    var IdHTTP := TIdHTTP.Create;
    try
      var jsonResponse := IdHTTP.Get(apiURL);

      Memo1.Lines.Text := jsonResponse;
    finally
      IdHTTP.Free;
    end;
  except
    on E: Exception do
      ShowMessage('Error: ' + E.Message);
  end;
end;

Then I get an error:

Project raised exception class EIdOSSLUnderlyingCryptoError with message 'Error connecting with SSL. error:1409442E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version'

What does this mean and/or what am I doing wrong?

1

There are 1 answers

5
complete_stranger On

You need a TIdSSLIOHandlerSocketOpenSSL for https. Keep in mind you need the openssl libraries.

implementation

uses
  Idhttp, IdSSLOpenSSL;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  var apiURL := 'https://api.github.com/users/octocat';
  try
    var IdHTTP := TIdHTTP.Create;
    try
      var ssl := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP);
      ssl.SSLOptions.SSLVersions := [sslvTLSv1_2];
      IdHTTP.IOHandler := ssl;

      var jsonResponse := IdHTTP.Get(apiURL);

      Memo1.Lines.Text := jsonResponse;
    finally
      IdHTTP.Free;
    end;
  except
    on E: Exception do
      ShowMessage('Error: ' + E.Message);
  end;
end;