if you're using the Drive API library, it will handle the 401 exceptions for you, as long as you give it a credential with access and refresh token.
Here's how to build a Credential
object with the StoredCredential
. You can use an implementation different than MemoryDataStoreFactory
:
public class ApiCredentialManager {
private DataStore<StoredCredential> dataStore;
//Put your scopes here
public static String[] SCOPES_ARRAY = { "https://www.googleapis.com/auth/admin.directory.user" };
private ApiCredentialManager() {
try {
dataStore = MemoryDataStoreFactory.getDefaultInstance().getDataStore("credentialDatastore");
} catch (IOException e) {
throw new RuntimeException("Unable to create in memory credential datastore", e);
}
}
public static ApiCredentialManager getInstance() {
if (instance == null)
instance = new ApiCredentialManager();
return instance;
}
public Credential getCredential(String username) throws Exception {
try {
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory())
.addRefreshListener(
new DataStoreCredentialRefreshListener(
username, dataStore))
.build();
if(dataStore.containsKey(username)){
StoredCredential storedCredential = dataStore.get(username);
credential.setAccessToken(storedCredential.getAccessToken());
credential.setRefreshToken(storedCredential.getRefreshToken());
}else{
//Do something of your own here to obtain the access token.
//Most usually redirect the user to the OAuth page
}
return credential;
} catch (GeneralSecurityException e) {
throw new Exception("isuue while setting credentials", e);
} catch (IOException e) {
e.printStackTrace();
throw new Exception("isuue while setting credentials", e);
}
}
//Call this when you've obtained the access token and refresh token from Google
public void saveCredential(String username, Credential credential){
StoredCredential storedCredential = new StoredCredential();
storedCredential.setAccessToken(credential.getAccessToken());
storedCredential.setRefreshToken(credential.getRefreshToken());
dataStore.set(username, storedCredential);
}
}