Killerpixler Killerpixler - 1 month ago 9
Java Question

Stored Credential from google api to be reused java

I have successfully authorized my desktop application. It stores a file called

. In order to not have to keep doing the copy URL into browser, accept, etc., steps every time I run the app, I want to use the credentials that I already have stored.

My code so far:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
System.out.println("flow success");

String url = flow

System.out.println("Please open the following URL in your browser then "
+ "type the authorization code:");

System.out.println(" " + url);

BufferedReader br = new BufferedReader(new InputStreamReader(;

String code = br.readLine();

GoogleTokenResponse tokenResponse
= flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();

GoogleCredential credential = new GoogleCredential
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory())
.addRefreshListener(new CredentialRefreshListener() {
public void onTokenResponse(
Credential credential,
TokenResponse tokenResponse) throws IOException {

System.out.println("Token Refreshed Succesfully");

public void onTokenErrorResponse(
Credential credential,
TokenErrorResponse tokenErrorResponse) throws IOException {

System.out.println("ERROR WITH TOKEN WTF?");

How do I read the stored credential and bypass the command line prompt?

I was thinking something like:

if (stored cred exists) {
try {
// use
} catch {
// prompt the user


You can create GoogleCredential object from stored credentials like this:

HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();
        GoogleCredential credential = new GoogleCredential.Builder()
                .setClientSecrets("client_id", "client_secret").build();