Search code examples
delphidelphi-10.2-tokyo

retrieve a json result from a https site


How can I retrieve a JSON result from a HTTPS site?

I prefer a method to no need any DLL.

It show this error:

Error connecting with SSL.error:1409442E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version.

I'm using Delphi Tokyo 10.2.

function GetUrlContent(s: string): string;
var
  IdHTTP1: TIdHTTP;
begin
  IdHTTP1 := TIdHTTP.Create;
  try
    Result := IdHTTP1.Get(s);
  finally
    IdHTTP1.Free;
  end;
end;

procedure GetData;
var
  mydata, ordername: string;
begin
  ordername := 'https://www.bitstamp.net/api/ticker/';
  mydata := GetUrlContent(ordername);
  DBMemo7.Text := mydata;
end;

I've also tried this, but it still gets the annoying SSL error:

function GetURLAsStrin1(const aurl:  string): string;
var
  res, req: String;
  sList: TStringList;
  IdHttp: TIdHttp;
begin
  IdHttp := TIdHttp.Create (nil);
  try
    IdHttp.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHttp);

    req := aurl;
    res := IdHttp.Get (req);

    result := res;
  finally
    idHttp.Free;
  end;

Solution

  • By default, TIdSSLIOHandlerSocketOpenSSL enables only TLS 1.0. Most likely, the site in question does not support TLS 1.0 anymore. Try enabling TLS 1.1 and 1.2, eg:

    function GetUrlContent(url: string): string;
    var
      IdHTTP1: TIdHTTP;
    begin
      IdHTTP1 := TIdHTTP.Create;
      try
        IO := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
        IO.SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2] // <-- add this!
        IdHttp.IOHandler := IO;
        Result := IdHTTP1.Get(url);
      finally
        IdHTTP1.Free;
      end;
    end;