Contents · Forum Home · StreamSec Tools 4.1.5.364 documentation

Download a page over HTTPS

TsmHTTPSClient is a complete HTTPS client: it connects, checks the server's certificate and host name, negotiates HTTP/1.1 or HTTP/2, follows safe redirects and hands back the response. It carries its own TLS engine, so it needs nothing else on the form.

The components on this page are normally placed on a form or a data module at design time and set up in the Object Inspector. The sample creates them in code instead, because code shows at a glance which properties are changed from their default values.

The units

uses
  System.SysUtils,
  StreamSec.Http.Client,          // tHttpResponse
  StreamSec.Mobile.HTTPSClient,   // TsmHTTPSClient
  StreamSec.Mobile.CCADB;         // TsmCCADBTrustAnchors: the public web roots

The client links the TLS and cryptography units it needs itself.

Set up the client

A client talks to one server: the one named by its Host and Port properties. Before it can check that server's certificate it needs to know which certificate authorities to believe. For a server whose CA you know:

{ A server whose certificate comes from a CA you know - your own servers, a
  partner's API, a device. Trust exactly that CA and nothing else. }
function NewClientForCA(const aHost, aCAFile: string; aPort: Integer): TsmHTTPSClient;
begin
  Result := TsmHTTPSClient.Create(nil);
  try
    { DER or PEM, told apart by content; a PEM bundle loads every
      certificate in it. The result is how many were loaded: 0 would leave
      the client trusting nobody, which fails at the first request instead. }
    if Result.TLSServer.LoadRootCertsFromFile(aCAFile) = 0 then
      raise eHTTPSClientError.CreateFmt('No certificate in %s', [aCAFile]);
    Result.Host := aHost;   // checked against the server's certificate
    Result.Port := aPort;
  except
    Result.Free;
    raise;
  end;
end;

For a server on the public web, and for when to use which, see Choose which servers a client trusts.

The host name is checked

On every connection the client checks that the server's certificate is issued for the name in Host. Nothing has to be set for it, and a certificate for another name ends the handshake. The rules are those of CheckDNSName, wildcards included: see Read a certificate file.

The check compares DNS names, so give Host the DNS name the certificate carries - www.example.com - and not the server's IP address. With an IP address in Host the connection fails, although the server's certificate is valid: a certificate for www.example.com does not cover the address the name resolves to.

To connect by address - the server has no DNS name, or the name resolves somewhere else - keep the address in Host and set ServerName to the name the certificate carries. The client sends that name to the server, which picks its certificate by it, and checks the certificate against it:

{ A server reached by its IP address. Host is where to connect; ServerName is
  the name the certificate is issued for, which the client sends to the
  server and checks the certificate against. }
function NewClientForAddress(const aAddress, aCertificateName, aCAFile: string;
  aPort: Integer): TsmHTTPSClient;
begin
  Result := NewClientForCA(aAddress, aCAFile, aPort);
  Result.ServerName := aCertificateName;
end;

The URLs then name the address too, because they name the client's own server: https://192.0.2.10/status.

Send the request

function GetText(aClient: TsmCustomHTTPSClient; const aURL: string;
                 out aStatus: Integer): string;
var
  lResponse: tHttpResponse;
begin
  { One client talks to one origin - its Host and Port; the URL names a path
    on it. An error status such as 404 is an ordinary response, not an
    exception; a failed connection, handshake or certificate check raises. }
  lResponse := aClient.Get(aURL);
  try
    aStatus := lResponse.StatusCode;
    Result := TEncoding.UTF8.GetString(lResponse.Body);
  finally
    lResponse.Free;
  end;
end;
{ The whole exchange: a client for one server, one request, the client freed. }
function FetchText(const aHost, aCAFile, aPath: string; aPort: Integer): string;
var
  lClient: TsmHTTPSClient;
  lStatus: Integer;
begin
  lClient := NewClientForCA(aHost, aCAFile, aPort);
  try
    Result := GetText(lClient, 'https://' + aHost + aPath, lStatus);
    if lStatus <> 200 then
      raise eHTTPSClientError.CreateFmt('%s%s answered %d', [aHost, aPath, lStatus]);
  finally
    lClient.Free;
  end;
end;

Redirects

Get follows a redirect (301, 302, 303, 307, 308) up to MaxRedirects hops, 5 by default. It never follows one to an http URL, and it removes Authorization and Cookie before a hop to another server. A hop to another server moves the client there: Host and Port take that server's values, and a later request for the first server is refused until you set them back. With the default RedirectPolicy, only GET and HEAD are followed; see Post JSON to an HTTPS API.

HTTP/1.1, HTTP/2 and HTTP/3

Protocols lists what the client offers, [hcpHttp11, hcpHttp2] by default; the server chooses, and Wire says what it chose. Add hcpHttp3 to let the client move to HTTP/3 when a server advertises it: it learns the alternative from a response's Alt-Svc field, tries QUIC on a later request and falls back to TCP if QUIC does not connect within Http3AttemptTimeout. HTTP/3 alone is refused, since TCP is needed both to learn the alternative and to fall back to.

The HTTPS client notes cover streaming, uploads, limits and the lifetime rules in full.

Reference

TsmHTTPSClient · StreamSec.Mobile.HTTPSClient

Related tasks