Chilkat Examples

ChilkatHOME.NET Core C#Android™AutoItCC#C++Chilkat2-PythonCkPythonClassic ASPDataFlexDelphi ActiveXDelphi DLLGoJavaLianjaMono C#Node.jsObjective-CPHP ActiveXPHP ExtensionPerlPowerBuilderPowerShellPureBasicRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++VB.NETVBScriptVisual Basic 6.0Visual FoxProXojo Plugin

Unicode C Examples

Web API Categories

ASN.1
AWS KMS
AWS Misc
Amazon EC2
Amazon Glacier
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Key Vault
Azure Service Bus
Azure Table Service
Base64
Bounced Email
Box
CAdES
CSR
CSV
Certificates
Cloud Signature CSC
Code Signing
Compression
DKIM / DomainKey
DNS
DSA
Diffie-Hellman
Digital Signatures
Dropbox
Dynamics CRM
EBICS
ECC
Ed25519
Email Object
Encryption
FTP
FileAccess
Firebase
GMail REST API
GMail SMTP/IMAP/POP
Geolocation
Google APIs
Google Calendar
Google Cloud SQL
Google Cloud Storage
Google Drive
Google Photos
Google Sheets
Google Tasks
Gzip
HTML-to-XML/Text
HTTP

HTTP Misc
IMAP
JSON
JSON Web Encryption (JWE)
JSON Web Signatures (JWS)
JSON Web Token (JWT)
Java KeyStore (JKS)
MHT / HTML Email
MIME
MS Storage Providers
Microsoft Graph
Misc
NTLM
OAuth1
OAuth2
OIDC
Office365
OneDrive
OpenSSL
Outlook
Outlook Calendar
Outlook Contact
PDF Signatures
PEM
PFX/P12
PKCS11
POP3
PRNG
REST
REST Misc
RSA
SCP
SCard
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
ScMinidriver
SharePoint
SharePoint Online
Signing in the Cloud
Socket/SSL/TLS
Spider
Stream
Tar Archive
ULID/UUID
Upload
WebSocket
XAdES
XML
XML Digital Signatures
XMP
Zip
curl
uncategorized

 

 

 

(Unicode C) Refresh Access Token on 401 Unauthorized and Retry (Service Account)

See more Google Cloud Storage Examples

Demonstrates how to handle an expired access token error, refresh the token, and retry the request. (In this case, the request is to download an object from Google Cloud Storage.)

Chilkat C/C++ Library Downloads

MS Visual C/C++

Linux/CentOS C/C++

Alpine Linux C/C++

MAC OS X C/C++

armhf/aarch64 C/C++

C++ Builder

iOS C/C++

Android C/C++

Solaris C/C++

MinGW C/C++

#include <C_CkStringBuilderW.h>
#include <C_CkHttpW.h>
#include <C_CkBinDataW.h>
#include <C_CkFileAccessW.h>
#include <C_CkAuthGoogleW.h>
#include <C_CkSocketW.h>

void ChilkatSample(void)
    {
    HCkStringBuilderW sbToken;
    BOOL success;
    HCkHttpW http;
    const wchar_t *url;
    HCkBinDataW fileData;
    int responseCode;
    HCkFileAccessW fac;
    const wchar_t *jsonKey;
    HCkAuthGoogleW gAuth;
    HCkSocketW tlsSock;
    HCkStringBuilderW sbErrorResponse;

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

    // This example uses a previously obtained access token having permission for the 
    // scope "https://www.googleapis.com/auth/cloud-platform"

    // In this example, Get Google Cloud Storage OAuth2 Access Token, 
    // the service account access token was saved to a text file.  This example fetches the access token from the file..
    sbToken = CkStringBuilderW_Create();
    success = CkStringBuilderW_LoadFile(sbToken,L"qa_data/tokens/googleCloudStorageAccessToken.txt",L"utf-8");
    if (success == FALSE) {
        wprintf(L"Failed to load access token.\n");
        CkStringBuilderW_Dispose(sbToken);
        return;
    }

    http = CkHttpW_Create();

    CkHttpW_putAuthToken(http,CkStringBuilderW_getAsString(sbToken));

    // Construct a URL to download an object named "starfish.jpg" from the "chilkat-ocean" bucket.
    CkHttpW_SetUrlVar(http,L"bucket_name",L"chilkat-ocean");
    CkHttpW_SetUrlVar(http,L"object_name",L"starfish.jpg");
    url = L"https://www.googleapis.com/storage/v1/b/{$bucket_name}/o/{$object_name}?alt=media";

    // If there is an error response, then we didn't actually download the file data,
    // but instead we downloaded an error response..
    fileData = CkBinDataW_Create();
    success = CkHttpW_DownloadBd(http,url,fileData);
    responseCode = CkHttpW_getLastStatus(http);
    if ((success == FALSE) && (responseCode != 401)) {
        wprintf(L"%s\n",CkHttpW_lastErrorText(http));
        CkStringBuilderW_Dispose(sbToken);
        CkHttpW_Dispose(http);
        CkBinDataW_Dispose(fileData);
        return;
    }

    if (responseCode == 401) {
        wprintf(L"Received 401 Unauthorized response. Attempting to refresh the access token...\n");

        // May be that the access token expired.
        // Load our JSON key and request a new access token, then retry the original request.
        fac = CkFileAccessW_Create();
        jsonKey = CkFileAccessW_readEntireTextFile(fac,L"qa_data/googleApi/ChilkatCloud-13a07a2e8b3f.json",L"utf-8");
        if (CkFileAccessW_getLastMethodSuccess(fac) != TRUE) {
            wprintf(L"%s\n",CkFileAccessW_lastErrorText(fac));
            CkStringBuilderW_Dispose(sbToken);
            CkHttpW_Dispose(http);
            CkBinDataW_Dispose(fileData);
            CkFileAccessW_Dispose(fac);
            return;
        }

        gAuth = CkAuthGoogleW_Create();
        CkAuthGoogleW_putJsonKey(gAuth,jsonKey);
        CkAuthGoogleW_putScope(gAuth,L"https://www.googleapis.com/auth/cloud-platform");
        CkAuthGoogleW_putExpireNumSeconds(gAuth,3600);
        CkAuthGoogleW_putSubEmailAddress(gAuth,L"");

        tlsSock = CkSocketW_Create();
        success = CkSocketW_Connect(tlsSock,L"www.googleapis.com",443,TRUE,5000);
        if (success != TRUE) {
            wprintf(L"%s\n",CkSocketW_lastErrorText(tlsSock));
            CkStringBuilderW_Dispose(sbToken);
            CkHttpW_Dispose(http);
            CkBinDataW_Dispose(fileData);
            CkFileAccessW_Dispose(fac);
            CkAuthGoogleW_Dispose(gAuth);
            CkSocketW_Dispose(tlsSock);
            return;
        }

        success = CkAuthGoogleW_ObtainAccessToken(gAuth,tlsSock);
        if (success != TRUE) {
            wprintf(L"%s\n",CkAuthGoogleW_lastErrorText(gAuth));
            CkStringBuilderW_Dispose(sbToken);
            CkHttpW_Dispose(http);
            CkBinDataW_Dispose(fileData);
            CkFileAccessW_Dispose(fac);
            CkAuthGoogleW_Dispose(gAuth);
            CkSocketW_Dispose(tlsSock);
            return;
        }

        CkFileAccessW_WriteEntireTextFile(fac,L"qa_data/tokens/googleCloudStorageAccessToken.txt",CkAuthGoogleW_accessToken(gAuth),L"utf-8",FALSE);

        // Retry the original request.
        CkHttpW_putAuthToken(http,CkAuthGoogleW_accessToken(gAuth));
        success = CkHttpW_DownloadBd(http,url,fileData);
        if (success == FALSE) {
            wprintf(L"%s\n",CkHttpW_lastErrorText(http));
            CkStringBuilderW_Dispose(sbToken);
            CkHttpW_Dispose(http);
            CkBinDataW_Dispose(fileData);
            CkFileAccessW_Dispose(fac);
            CkAuthGoogleW_Dispose(gAuth);
            CkSocketW_Dispose(tlsSock);
            return;
        }

    }

    if (responseCode != 200) {
        // Get the error response
        sbErrorResponse = CkStringBuilderW_Create();
        CkStringBuilderW_AppendBd(sbErrorResponse,fileData,L"utf-8",0,0);
        wprintf(L"Error response code = %d\n",responseCode);
        wprintf(L"Error:\n");
        wprintf(L"%s\n",CkStringBuilderW_getAsString(sbErrorResponse));
        CkStringBuilderW_Dispose(sbToken);
        CkHttpW_Dispose(http);
        CkBinDataW_Dispose(fileData);
        CkFileAccessW_Dispose(fac);
        CkAuthGoogleW_Dispose(gAuth);
        CkSocketW_Dispose(tlsSock);
        CkStringBuilderW_Dispose(sbErrorResponse);
        return;
    }

    wprintf(L"Success.\n");

    // Save the downloaded data to a file.
    success = CkBinDataW_WriteFile(fileData,L"qa_output/starfish.jpg");


    CkStringBuilderW_Dispose(sbToken);
    CkHttpW_Dispose(http);
    CkBinDataW_Dispose(fileData);
    CkFileAccessW_Dispose(fac);
    CkAuthGoogleW_Dispose(gAuth);
    CkSocketW_Dispose(tlsSock);
    CkStringBuilderW_Dispose(sbErrorResponse);

    }

 

© 2000-2024 Chilkat Software, Inc. All Rights Reserved.