HttpTransport netTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleTokenResponse token;
try {
token = new GoogleAuthorizationCodeTokenRequest(
netTransport,
jsonFactory,
CLIENT_ID,
CLIENT_SECRET,
CODE,
REDIRECT).execute();
GoogleCredential cd = new GoogleCredential().setAccessToken(token
.getAccessToken());
Plus plus = Plus
.builder(new NetHttpTransport(), new JacksonFactory())
.setApplicationName(APP_NAME)
.setHttpRequestInitializer(cd).build();
Person profile = plus.people().get("me").execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
大家好,我正在尝试从我的Google App Engine应用程序中获取Google +的一些用户信息,但我仍然坚持要放置/如何获取GoogleAuthorizationCodeTokenRequest的CODE参数。任何帮助是极大的赞赏。谢谢。
答案 0 :(得分:0)
您可以从重定向网址获取de CODE。
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
Arrays.asList(DriveScopes.DRIVE)).setAccessType("offline").setApprovalPrompt("auto").build();
String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
res.sendRedirect(url);
答案 1 :(得分:0)
我会尝试提高雷米泰科纳的答案。 基本的oAuth授权流程是:
urn:ietf:wg:oauth:2.0:oob:auto
作为网址。当用户授予访问权限时,您的应用应该从网页标题中读取访问代码。urn:ietf:wg:oauth:2.0:oob
作为REDIRECT_URL。当用户授予访问权限时,他将被重定向到包含访问代码的页面,并请求将其复制并粘贴到您的应用程序中。您可以在此处找到详细信息:https://developers.google.com/identity/protocols/OAuth2InstalledApp?hl=RU#choosingredirecturi
小例子:
GoogleAuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow
.Builder(httpTransport, jsonFactory, clientId, clientSecret, scopes)
.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);
}
答案 2 :(得分:0)
以下是您要从google api获取代码
List<String> responsetype = Arrays.asList("code");
// Step 1: Authorize -->
String authorizationUrl = new GoogleBrowserClientRequestUrl(clientId, redirectUrl, Arrays.asList(scope))
.setResponseTypes(responsetype)
.build();
// Point or redirect your user to the authorizationUrl.
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
它将从浏览器返回一个Url点击网址,您将在响应中获得代码。