Google API Java客户端 - 获取用户信息

时间:2012-12-11 03:33:59

标签: java google-api google-drive-api google-api-java-client

我在Google API Java客户端库1.12.0-beta版中找出看似简单的任务时遇到了麻烦。我可以使用OAuth2进行身份验证,并可以检索和操作我的应用程序所需的Google云端硬盘部分。不过,我想关注Google best practices并在我的应用顶部显示基本用户信息。

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

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

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

我认为您正在混淆Drip API和OAuth API。

用户信息可以通过以下方式从Drive 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

答案 1 :(得分:0)

对于任何看起来像我一样的人,你需要:

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

专业提示:当您拥有Java类名称时,请转到Maven Central,高级搜索以及类名称的seearch。它将列出包含该类的所有库。您可以使用完全限定名称,也可以只使用类名。即使您不使用maven,也可以从那里下载jar文件。

答案 2 :(得分:0)

以下是在java中使用OAuth 2获取userinfo的示例 如果您将Google云端硬盘添加到SCOPE(例如https://www.googleapis.com/auth/drive.file),您甚至可以访问Google云端硬盘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);}
相关问题