Set up the client as in Download a page over HTTPS, then send the body with Post, naming its content type.
function PostJson(aClient: TsmCustomHTTPSClient; const aURL, aJson: string; out aStatus: Integer): string; var lResponse: tHttpResponse; begin lResponse := aClient.Post(aURL, TEncoding.UTF8.GetBytes(aJson), 'application/json'); try aStatus := lResponse.StatusCode; Result := TEncoding.UTF8.GetString(lResponse.Body); finally lResponse.Free; end; end;
function PlaceOrder(aClient: TsmCustomHTTPSClient; const aURL: string; out aReply: string): Boolean; var lStatus: Integer; begin aReply := PostJson(aClient, aURL, '{"item":"A-100","quantity":2}', lStatus); { 201 Created is the usual answer to a new resource; 200 is accepted too. } Result := (lStatus = 200) or (lStatus = 201); end;
ServerName to the name in the certificate - see Download a page over HTTPS.With the default RedirectPolicy, hrpSafeMethods, a redirect answering a POST is not followed: the 3xx is returned as the response, so the request is never repeated somewhere you did not send it. hrpAll follows every method; a 303 then becomes a GET without a body, as HTTP defines it, and the other codes resend the method and body.
Execute takes any method, request fields of your own (an authorization field, for instance) and a body:
function PutJson(aClient: TsmCustomHTTPSClient; const aURL, aToken, aJson: string; out aReply: string): Integer; var lHeaders: tHttpHeaders; lResponse: tHttpResponse; begin lHeaders := tHttpHeaders.Create; try { Field names in lowercase: HTTP/2 refuses any other (RFC 9113 section 8.2.1), and HTTP/1.1 takes them in any case. } lHeaders.Add('authorization', 'Bearer ' + aToken); lResponse := aClient.Execute('PUT', aURL, lHeaders, TEncoding.UTF8.GetBytes(aJson)); try Result := lResponse.StatusCode; aReply := TEncoding.UTF8.GetString(lResponse.Body); finally lResponse.Free; end; finally lHeaders.Free; end; end;
Write field names in lowercase. HTTP/2 allows no other (RFC 9113 section 8.2.1), and on an HTTP/2 connection the client raises EHttp2FrameError before it sends a request that has one; HTTP/1.1 takes them in any case.
A body too large to build in memory goes through BeginUpload or BeginStreamed; the HTTPS client notes describe both.
TsmHTTPSClient · StreamSec.Mobile.HTTPSClient