81,092
社区成员
发帖
与我相关
我的任务
分享
private static final Collection<String> SCOPE = Arrays.asList("https://www.googleapis.com/auth/urlshortener");
private static final String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";
private static final HttpTransport TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final String CLIENT_ID = "xxxxx"; //use your client ID
private static final String CLIENT_SECRET = "xxxxx"; //use your client secret
GoogleAuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow
.Builder(TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, SCOPE)
.setCredentialDataStore(new MemoryDataStoreFactory().getDataStore("tokens"))
.build();
String userId = "user-id";
Credential credential = authorizationCodeFlow.loadCredential(userId);
if (credential == null) {
GoogleAuthorizationCodeRequestUrl authorizationUrl = authorizationCodeFlow.newAuthorizationUrl();
authorizationUrl.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI);
//LOGGER.error("Please, authorize application. Visit {}", authorizationUrl);
Scanner s = new Scanner(System.in);
String code = s.nextLine();
GoogleAuthorizationCodeTokenRequest tokenRequest = authorizationCodeFlow.newTokenRequest(code);
tokenRequest.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI);
GoogleTokenResponse tokenResponse = tokenRequest.execute();
credential = authorizationCodeFlow.createAndStoreCredential(tokenResponse, userId);