API Reference
StreamSec.Http.Client
Minimal HTTP/1.1 Client Unit
Feature notes: HTTPS application layer notes (HTTP/1.1, h2, h3)
Classes, interfaces and records
classeHttpError
inherits from Exception
eHttpError signals a transport-level failure of the client: a socket, TLS handshake, response-framing, redirect-limit or MaxResponseSize error. An ordinary HTTP error status (4xx/5xx) is NOT raised this way - it arrives as a normal tHttpResponse, so applications wrap Execute/Get/Head/Post in a try/except for eHttpError and separately inspect StatusCode.
(no public members)
(no public members)
classtHttpChunkDecoder
Incremental chunked decoding shared by the one-shot and persistent wires. Feed returns only decoded octets from that block. It never retains chunk data, so even one-byte chunks do not accumulate their framing in memory. MaxMetadataBytes bounds each size/extension line and the complete trailer section; zero disables a policy limit. MaxBodyBytes counts decoded octets.
constructor Create(aMaxBodyBytes, aMaxMetadataBytes: Integer); overload;
constructor Create(aMaxBodyBytes, aMaxMetadataBytes: Integer; const aInitialHeaders: tHttpHeaders); overload;
destructor Destroy; override;
function TakeTrailers: tHttpHeaders;
Once Done, hands over the trailer fields received after the last chunk (an empty list when there were none); the caller then owns and frees it, and a second call returns nil. Raises eHttpError before Done, so a partial section is never seen.
procedure Feed(const aBuf: tBytes; aStart, aCount: Integer; out aBody: tBytes);
function Done: Boolean;
Returns the logical negation of fFailed and (fState = hcsDone).
property MaxBodyBytes: Integer read fMaxBodyBytes write fMaxBodyBytes;
property MaxMetadataBytes: Integer read fMaxMetadataBytes write fMaxMetadataBytes;
tHttpHeaders is an ordered multimap. A TStrings with Name=Value semantics would be the obvious choice but is wrong here: HTTP permits a field name to repeat, and ACME relies on that for Link, where the "up" and "alternate" relations arrive as separate headers. Lookups are case-insensitive because field names are.
Creates an empty multimap. Applications normally read a populated set via tHttpResponse.Headers rather than constructing one directly.
Frees the backing name and value lists.
Discards all fields, so a collection can be reused.
Appends a field, preserving arrival order and allowing the same name to recur (as HTTP permits for Link, Set-Cookie, etc.). The response parser calls this while reading the header block.
IndexOf returns the index of the first field named aName at or after aFrom, or -1. Pass the previous result + 1 to walk repeated fields.
Returns the value of the first field with this name, or '' if absent.
Like Value but returns aDefault when the field is absent, letting the caller distinguish a missing header from a present-but-empty one.
True when at least one field of this name is present; used to branch on optional headers such as Content-Length.
Appends every value of a repeated field to aDest in wire order - needed for headers that legitimately recur, e.g. collecting all Link relations.
Number of stored fields, counting each repeat separately.
The field name at aIndex, in the order received.
The field value at aIndex; the setter is used by the parser to extend a value in place when unfolding an obsolete continuation line.
classtHttpResponse
constructor Create;
Creates the response with an empty Headers collection. The client builds and returns the instance; the caller owns it and must Free it.
destructor Destroy; override;
Frees the owned Headers collection.
Convenience for Headers.Value: the first value of the named field, or '' if it was not sent.
procedure PublishTrailers(var aTrailers: tHttpHeaders);
Called by the client code that reads the wire, once the response has completed successfully; an application reading responses never calls it. The response takes ownership of aTrailers, sets it to nil and shows it as Trailers (nil publishes an empty section). Raises eHttpError on a second call, or when aTrailers is a collection this response returned.
function ContentType: string;
The Content-Type media type with any parameters (e.g. "; charset=...") and surrounding whitespace removed, so it can be compared directly to a type such as application/json.
function Link(const aRel: string): string;
Link returns the first target URI whose Link header carries the given relation, or '' if there is none. RFC 8288 allows both one header per relation and several comma-separated values in one header; both are handled, and a rel with multiple space-separated tokens matches if any token matches.
procedure Links(const aRel: string; aDest: TStrings);
Appends every Link target URI matching aRel to aDest, gathering matches across both repeated Link headers and comma-separated values in one - use it when a relation can appear more than once, e.g. ACME's "alternate" certificate chains.
function RetryAfter(aDefaultSeconds: Integer): Integer;
RetryAfter returns the delta-seconds form of the header. The HTTP-date form is not parsed - it is vanishingly rare on the APIs this client targets - and yields aDefaultSeconds instead.
function BodyAsUTF8: string;
Decodes the body octets as UTF-8 text - the usual accessor for a JSON or otherwise textual response.
function StatusIsSuccess: Boolean;
True for a 2xx status; a quick success test before reading the body.
property StatusCode: Integer read fStatusCode write fStatusCode;
The parsed numeric status code and the primary thing to inspect, since an HTTP error status is delivered here rather than raised as an exception. The setter exists so the parser can populate it.
property StatusText: string read fStatusText write fStatusText;
The reason phrase from the status line (may be empty); informational.
The parsed response header multimap; see tHttpHeaders for lookups.
property Trailers: tHttpHeaders read GetTrailers;
The trailer fields that followed the body, kept apart from Headers. Empty until the response has completed successfully: once Execute (or Get, Head, Post) has returned it, or, on an iHttpExchange, once Read has returned 0 or ReadAll has returned. A reference fetched earlier stays empty, so fetch the property again. Owned by the response: treat it as read-only and never free it.
property Body: tBytes read fBody write fBody;
The raw response body, already de-chunked and Content-Length-trimmed.
property FinalURL: string read fFinalURL write fFinalURL;
FinalURL is the URL the response actually came from, which differs from the requested URL when redirects were followed.
classtHttpClient
constructor Create;
Constructs a client seeded with the default timeout, user agent, redirect and response-size limits (the cHttpDefault* constants); adjust the properties below afterwards.
destructor Destroy; override;
procedure Cancel;
Cancel is safe from another thread. It stays in force: the running request and every later one raise eHttpError until ResetCancel, which must be called only while no request is running.
Full description »
procedure ResetCancel;
function Execute(aMethod: tHttpMethod; const aURL: string; const aBody: tBytes; const aContentType, aAccept: string): tHttpResponse;
Execute performs the request, following redirects for GET and HEAD up to MaxRedirects. It raises eHttpError on transport, framing or redirect-limit failures; an HTTP error status is NOT an exception - inspect StatusCode.
function Get(const aURL: string; const aAccept: string = ''): tHttpResponse;
Issues a GET and follows redirects; aAccept, when set, becomes the Accept header. The common entry point for fetching a resource.
function Head(const aURL: string): tHttpResponse;
Issues a HEAD (status and headers, no body) and follows redirects - use it to probe a resource's existence or metadata cheaply.
function Post(const aURL: string; const aBody: tBytes; const aContentType: string; const aAccept: string = ''): tHttpResponse;
Issues a POST carrying aBody with the given aContentType. Unlike Get/Head a POST is never auto-redirected: a 3xx is handed back verbatim, because a signed protocol (e.g. ACME's JWS "url" header) binds the request URL.
property Timeout: Cardinal read fTimeout write fTimeout;
Per-receive socket wait in milliseconds, applied to each read including the TLS handshake. A stall usually surfaces as an eHttpError; the one exception is a body delimited only by connection close, where a timeout is indistinguishable from the peer finishing and yields the bytes so far.
property RequestTimeout: Cardinal read fRequestTimeout write fRequestTimeout;
Absolute request budget across DNS, TCP, TLS, response and redirects. Zero leaves each I/O to Timeout alone, unless DeadlineTick is set. A request with a deadline must not run in a library's initialization or finalization (DllMain): its lookup thread cannot start there. A DLL or package that ran such requests with DnsServers empty must follow HostLookupShutdown.txt before it is unloaded.
property DeadlineTick: UInt64 read fAbsoluteDeadlineTick write fAbsoluteDeadlineTick;
Optional monotonic deadline shared by several requests. Zero disables it. Read the clock with stTlsUtils.GetTickCount64; each Execute uses the earlier of this deadline and its own RequestTimeout.
property TLSServer: TsmCustomTLSInternalServer read fTLSServer write fTLSServer;
Optional explicit HTTPS engine; nil uses the existing GlobalServer. The caller keeps this engine alive through the final request.
property SourceIP: string read fSourceIP write fSourceIP;
property DnsServers: TStringList read fDnsServers;
For requests with a deadline (RequestTimeout or DeadlineTick). Empty, the default: the host name is looked up with the operating system's resolver, as without a deadline - the hosts file, the system's DNS servers, its cache - and waited for no longer than the deadline allows.
Full description »
property HostResolver: tHostResolveFunc read fHostResolver write fHostResolver;
For requests with a deadline and DnsServers empty: a resolver run in the system's place, on the lookup's own thread (see stSocket.tHostResolveFunc). nil, the default, is the system's.
property UserAgent: string read fUserAgent write fUserAgent;
Text sent in the User-Agent request header; set it to '' to omit the header entirely.
property MaxRedirects: Integer read fMaxRedirects write fMaxRedirects;
Maximum number of redirect hops taken for GET/HEAD before Execute gives up with an eHttpError.
property MaxResponseSize: Integer read fMaxResponseSize write fMaxResponseSize;
MaxResponseSize bounds the buffer a hostile or malfunctioning server can make this client allocate; exceeding it raises eHttpError.
Types (enumerations, sets, aliases)
enumtHttpChunkState
tHttpChunkState = (hcsSize, hcsSizeLF, hcsData, hcsDataEnd, hcsDataLF,
hcsTrailers, hcsTrailersLF, hcsDone);
enumtHttpMethod
The request method passed to Execute. Get, Head and Post are thin wrappers that select hmGET, hmHEAD and hmPOST respectively; only hmGET and hmHEAD are ever auto-redirected.
tHttpMethod = (hmGET, hmPOST, hmHEAD);
Routines