2012-12-11 105 views
5

我无法在Google API Java客户端库版本1.12.0-beta中计算一个看似简单的任务。我可以使用OAuth2进行身份验证,并可以检索和操纵我的应用程序所需的Google Drive部分。不过,我想要关注Google best practices,并在我的应用顶部显示基本用户信息。Google API Java客户端 - 获取用户信息

我已经搜索了谷歌提供的文件迷宫,并搜索了很多其他网站以及似乎无法找到我需要的东西。我查看了最佳实践页面上建议的用户信息API。据我所知,它应该是我正在使用的Java客户端的一部分,但事实并非如此。我甚至发现一个full method example概述了我可能如何获取用户信息。它所引用的类 - Userinfo - 似乎不是我正在使用的客户端库中包含的任何库的一部分。我进一步搜索了解我是否缺少一个包含OAuth服务Java客户端的单独下载。

我认为我遇到的主要问题是找到当前版本的Java客户端库的相关信息。有没有其他人遇到过这个问题?我非常感谢任何关于如何获得基本用户信息的指针。

感谢您的帮助。

回答

0

我认为你在混合滴灌API和OAuth API。

用户信息可以从驱动器的API来获得:

(其中服务是您com.google.api.services.drive.Drive的实例)

About about = service.about().get().execute(); 
System.out.println("Current user name: " + about.getName()); 
System.out.println("Root folder ID: " + about.getRootFolderId()); 
System.out.println("Total quota (bytes): " + about.getQuotaBytesTotal()); 
System.out.println("Used quota (bytes): " + about.getQuotaBytesUsed()); 

https://developers.google.com/drive/v2/reference/about/get

0

对于任何人,因为我是,你需要:

<dependency> 
     <groupId>com.google.apis</groupId> 
     <artifactId>google-api-services-oauth2</artifactId> 
</dependency> 

专业提示:当哟你有一个Java类的名字,去Maven Central,高级搜索,并寻找类名称。它将列出包含该类的所有库。您可以使用完全限定名称或仅使用类名称。即使你不使用maven,你也可以从那里下载jar文件。

0

这里是获得用户信息在Java 使用OAuth 2的一个例子,如果你加入谷歌云端硬盘范围(如https://www.googleapis.com/auth/drive.file),你甚至可以访问谷歌云端硬盘API

完整的示例
https://github.com/riversun/google-login-servlet-example-simple

在servlet

 GoogleCredential credential = OAuthSession.getInstance().createCredential(req); 

     Oauth2 oauth2 = new Oauth2.Builder(
       new com.google.api.client.http.javanet.NetHttpTransport(), 
       new com.google.api.client.json.jackson2.JacksonFactory(), 
       credential).build(); 

     // Get userInfo using credential 
     Userinfoplus userInfo = oauth2.userinfo().get().execute(); 

在OAuthFilter

// Return OAuth2 scope you want to be granted to by users 
    @Override 
    protected List<String> getScopes() { 

     final String OAUTH2_SCOPE_MAIL = "email"; 
     final String OAUTH2_SCOPE_USERINFO_PROFILE = "https://www.googleapis.com/auth/userinfo.profile"; 

     return Arrays.asList(OAUTH2_SCOPE_MAIL, OAUTH2_SCOPE_USERINFO_PROFILE);}