【问题标题】:Google API Java Client - Get user infoGoogle API Java 客户端 - 获取用户信息
【发布时间】:2012-11-28 14:10:25
【问题描述】:

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

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

我认为我遇到的主要问题是查找当前版本的 Java 客户端库的相关信息。有没有其他人遇到过这个问题?对于如何获取基本用户信息的任何指示,我将不胜感激。

感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

    这是在 java 中使用 OAuth 2 获取用户信息的示例 如果您将 Google Drive 添加到 SCOPE(例如https://www.googleapis.com/auth/drive.file),您甚至可以访问 Google Drive API

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

    在小服务程序中

            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);}
    

    【讨论】:

      【解决方案2】:

      对于任何像我一样正在寻找的人,您需要:

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

      专业提示:如果您有 Java 类名,请转到 Maven Central、高级搜索,然后搜索类名。它将列出包含该类的所有库。您可以使用完全限定名或仅使用类名。即使不使用maven,也可以从那里下载jar文件。

      【讨论】:

        【解决方案3】:

        我认为您混淆了 Drip API 和 OAuth API。

        用户信息可通过以下方式从 Drive API 获取:

        (其中 service 是您的 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

        【讨论】:

          猜你喜欢
          • 2016-04-12
          • 1970-01-01
          • 2018-12-21
          • 1970-01-01
          • 2022-09-27
          • 1970-01-01
          • 2013-04-03
          • 2014-03-03
          • 2020-03-22
          相关资源
          最近更新 更多