Sample code for 30+ languages & platforms
Delphi DLL

SharePoint -- Get Server Form Digest Value

Demonstrates how to get a server form digest value to be placed in the X-RequestDigest HTTP request header for POST, PUT, MERGE, and DELETE requests. A form digest value is typically valid for 1800 seconds (i.e. 30 minutes). This example persists the value to a file, and only requests a new form digest value if the existing one is near expiration.

Chilkat Delphi DLL Downloads

Delphi DLL
uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Http, FileAccess, HttpResponse, Xml, CkDateTime;

...

procedure TForm1.Button1Click(Sender: TObject);
var
success: Boolean;
fac: HCkFileAccess;
xml: HCkXml;
dtExpire: HCkDateTime;
dtNow: HCkDateTime;
formDigestXmlFile: PWideChar;
tNow: Integer;
tExpire: Integer;
http: HCkHttp;
savedAccept: PWideChar;
resp: HCkHttpResponse;
xml2: HCkXml;
timeoutInSec: Integer;

begin
success := False;

// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

// First, let's see if we already have a persisted form digest value
// that hasn't yet expired.
fac := CkFileAccess_Create();
xml := CkXml_Create();

// My example code (below) persists the form digest XML in this format:
// 
// 	<savedFormDigestValue>
// 	<d:ExpireDateTime>2017-04-12T20:46:39Z</d:ExpireDateTime>
// 	<d:FormDigestValue>0x3059FFB920651834540F3E6792EA73F5746B302E953FF4E808E485DB1E6C2836C7CF924644995F092453B02A94DE14A7962674B7B16780AF16EAFB8C246BCDC7,12 Apr 2017 17:08:22 -0000</d:FormDigestValue>
// 	</savedFormDigestValue>
// 

dtExpire := CkDateTime_Create();
dtNow := CkDateTime_Create();

formDigestXmlFile := 'qa_data/sharepoint/savedFormDigestValue.xml';
if (CkFileAccess_FileExists(fac,formDigestXmlFile) = True) then
  begin

    CkXml_LoadXmlFile(xml,formDigestXmlFile);

    // Get the expire date/time
    CkDateTime_SetFromTimestamp(dtExpire,CkXml__getChildContent(xml,'d:ExpireDateTime'));

    // Get the current date/time
    CkDateTime_SetFromCurrentSystemTime(dtNow);

    // Get both times as Unix time values
    tNow := CkDateTime_GetAsUnixTime(dtNow,False);
    tExpire := CkDateTime_GetAsUnixTime(dtExpire,False);

    // If tNow >= tExpire, then fall through.
    // Otherwise, just use the cached digest value.
    if (tNow < tExpire) then
      begin
        Memo1.Lines.Add('Cached digest value is not yet expired.');
        Memo1.Lines.Add('X-RequestDigest: ' + CkXml__getChildContent(xml,'d:FormDigestValue'));
        Exit;
      end;

  end;

// If we got to this point, the cached digest value either does not exist, or expired.

http := CkHttp_Create();

// If SharePoint Windows classic authentication is used, then set the 
// Login, Password, LoginDomain, and NtlmAuth properties.
CkHttp_putLogin(http,'SHAREPOINT_USERNAME');
CkHttp_putPassword(http,'SHAREPOINT_PASSWORD');
CkHttp_putLoginDomain(http,'SHAREPOINT_NTLM_DOMAIN');
CkHttp_putNtlmAuth(http,True);

// The more common case is to use SharePoint Online authentication (via the SPOIDCRL cookie).
// If so, do not set Login, Password, LoginDomain, and NtlmAuth, and instead
// establish the cookie as shown at SharePoint Online Authentication

// When creating, updating, and deleting SharePoint entities, we'll need
// to first get the server's form digest value to send in the X-RequestDigest header.
// This can be retrieved by making a POST request with an empty body to
// http://<site url>/_api/contextinfo and extracting the value of the
// d:FormDigestValue node in the XML that the contextinfo endpoint returns.

// Apparently, SharePoint needs an "Accept" request header equal to "application/xml",
// otherwise SharePoint will return an utterly incomprehensible and useless error message.
savedAccept := CkHttp__accept(http);
CkHttp_putAccept(http,'application/xml');

// Note: The last argument ("utf-8") is meaningless here because the body is empty.
resp := CkHttpResponse_Create();
success := CkHttp_HttpStr(http,'POST','https://SHAREPOINT_HTTPS_DOMAIN/_api/contextinfo','','utf-8','application/xml',resp);
if (success = False) then
  begin
    Memo1.Lines.Add(CkHttp__lastErrorText(http));
    Exit;
  end;

// Restore the default Accept header
CkHttp_putAccept(http,savedAccept);

if (CkHttpResponse_getStatusCode(resp) <> 200) then
  begin
    // A response status code not equal to 200 indicates failure.
    Memo1.Lines.Add('Response status code = ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
    Memo1.Lines.Add('Response body:');
    Memo1.Lines.Add(CkHttpResponse__bodyStr(resp));
    Exit;
  end;

CkXml_LoadXml(xml,CkHttpResponse__bodyStr(resp));

// The response XML looks like this:

// <?xml version="1.0" encoding="utf-8" ?>
// <d:GetContextWebInformation xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml" m:type="SP.ContextWebInformation">
//     <d:FormDigestTimeoutSeconds m:type="Edm.Int32">1800</d:FormDigestTimeoutSeconds>
//     <d:FormDigestValue>0x3059FFB920651834540F3E6792EA73F5746B302E953FF4E808E485DB1E6C2836C7CF924644995F092453B02A94DE14A7962674B7B16780AF16EAFB8C246BCDC7,12 Apr 2017 17:08:22 -0000</d:FormDigestValue>
//     <d:LibraryVersion>15.0.4569.1000</d:LibraryVersion>
//     <d:SiteFullUrl>https://SHAREPOINT_HTTPS_DOMAIN</d:SiteFullUrl>
//     <d:SupportedSchemaVersions m:type="Collection(Edm.String)">
//         <d:element>14.0.0.0</d:element>
//         <d:element>15.0.0.0</d:element>
//     </d:SupportedSchemaVersions>
//     <d:WebFullUrl>https://SHAREPOINT_HTTPS_DOMAIN</d:WebFullUrl>
// </d:GetContextWebInformation>
// 

// Cache the digest value, and also an expiration time.  If this code is run again
// before the digest expires, we'll just get it from the file.
xml2 := CkXml_Create();

CkXml_putTag(xml2,'savedFormDigestValue');
CkXml_NewChild2(xml2,'d:FormDigestValue',CkXml__getChildContent(xml,'d:FormDigestValue'));

timeoutInSec := CkXml_GetChildIntValue(xml,'d:FormDigestTimeoutSeconds');
Memo1.Lines.Add('Timeout in seconds = ' + IntToStr(timeoutInSec));

// Convert this to an expire timestamp.
// Let's make it expire 30 seconds prior to the actual timeout, just to be safe.
if (timeoutInSec > 30) then
  begin
    timeoutInSec := timeoutInSec - 30;
  end;

CkDateTime_SetFromCurrentSystemTime(dtExpire);
CkDateTime_AddSeconds(dtExpire,timeoutInSec);
CkXml_NewChild2(xml2,'d:ExpireDateTime',CkDateTime__getAsTimestamp(dtExpire,False));

// Persist the digest and expire time to a file.
CkXml_SaveXml(xml2,formDigestXmlFile);

Memo1.Lines.Add('Here is the new form digest value:');
Memo1.Lines.Add('X-RequestDigest: ' + CkXml__getChildContent(xml,'d:FormDigestValue'));

CkFileAccess_Dispose(fac);
CkXml_Dispose(xml);
CkDateTime_Dispose(dtExpire);
CkDateTime_Dispose(dtNow);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(resp);
CkXml_Dispose(xml2);

end;