1
votes

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;
2

2 Answers

2
votes

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;
0
votes

For newer delphi versions, I would recommend using the in-built HttpClient class. It does not require any external DLLs, and works for both http or https out of the box.

uses
  System.Net.HttpClient;

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  Memo1.Text := GetUrlContent('https://www.bitstamp.net/api/ticker/');
end;

function TForm1.GetUrlContent(Url: string): string;
var
  HttpClient: THttpClient;
  Response: IHttpResponse;
begin
  HttpClient := THTTPClient.Create;
  try
    Response := HttpClient.Get(URL);
    Result := Response.ContentAsString();
  finally
    HttpClient.Free;
  end;
end;