// This callback URL will allow you to copy the token from the success screen.
private static final String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";
private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets)
throws Exception {
GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
new NetHttpTransport(),
new JacksonFactory(),
clientSecrets,
Lists.newArrayList(SCOPE))
// Set the access type to offline so that the token can be refreshed.
// By default, the library will automatically refresh tokens when it
// can, but this can be turned off by setting
// api.dfa.refreshOAuth2Token=false in your ads.properties file.
.setAccessType("offline").build();
String authorizeUrl =
authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
System.out.println("Paste this url in your browser: \n" + authorizeUrl + '\n');
// Wait for the authorization code.
System.out.println("Type the code you received here: ");
String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();
// Authorize the OAuth2 token.
GoogleAuthorizationCodeTokenRequest tokenRequest =
authorizationFlow.newTokenRequest(authorizationCode);
tokenRequest.setRedirectUri(CALLBACK_URL);
GoogleTokenResponse tokenResponse = tokenRequest.execute();
// Create the OAuth2 credential.
GoogleCredential credential = new GoogleCredential.Builder()