Sample code for 30+ languages & platforms
Java

Automatically Refresh Token for 401 Unauthorized

See more Google Calendar Examples

Demonstrates how to automatically refresh an access token (without user interaction) when the token expires and a 401 Unauthorized response is received.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.OAuth2;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        String tokenFilePath = "qa_data/tokens/googleCalendar.json";

        // Get our current access token.
        JsonObject jsonToken = new JsonObject();
        jsonToken.loadFile(tokenFilePath);
        if (!jsonToken.hasMember("access_token")) {
            System.out.println("No access token found.");
            return;
        }

        Http http = new Http();
        http.setAuthToken(jsonToken.stringOf("access_token"));

        String jsonResponse = null;
        try {
            jsonResponse = http.quickGetStr("https://www.googleapis.com/calendar/v3/users/me/calendarList");
        } catch (ChilkatException e) {
            if (http.getLastStatus() != 401) {
                System.out.println(e.getLastErrorText());
                System.out.println("----");
                System.out.println(http.getLastResponseBody());
                return;
            }

            // The access token must've expired.
            // Refresh the access token and then retry the request.
            OAuth2 oauth2 = new OAuth2();

            oauth2.setTokenEndpoint("https://www.googleapis.com/oauth2/v4/token");

            // Replace these with actual values.
            oauth2.setClientId("GOOGLE-CLIENT-ID");
            oauth2.setClientSecret("GOOGLE-CLIENT-SECRET");

            // Get the "refresh_token"
            oauth2.setRefreshToken(jsonToken.stringOf("refresh_token"));

            // Send the HTTP POST to refresh the access token..
            try {
                oauth2.refreshAccessToken();
            } catch (ChilkatException e2) {
                System.out.println(e2.getLastErrorText());
                return;
            }

            // The response contains a new access token, but we must keep
            // our existing refresh token for when we need to refresh again in the future.
            jsonToken.updateString("access_token", oauth2.getAccessToken());

            // Save the new JSON access token response to a file.
            StringBuilder sbJson = new StringBuilder();
            jsonToken.setEmitCompact(false);
            jsonToken.emitSb(sbJson);
            sbJson.writeFile(tokenFilePath, "utf-8", false);

            System.out.println("OAuth2 authorization granted!");
            System.out.println("New Access Token = " + oauth2.getAccessToken());

            // re-try the original request.
            http.setAuthToken(oauth2.getAccessToken());
            try {
                jsonResponse = http.quickGetStr("https://www.googleapis.com/calendar/v3/users/me/calendarList");
            } catch (ChilkatException e2) {
                System.out.println(e2.getLastErrorText());
                return;
            }
        }

        System.out.println(jsonResponse);
        System.out.println("-----------------------------");
    }
}