使用 Microsoft Graph 列出 Java 应用中的用户

在本文中,你将扩展在 使用 Microsoft Graph 生成 Java 应用时 创建的应用程序,并使用 Microsoft Graph 用户 API 进行仅限应用的身份验证。 使用 Microsoft Graph 列出组织中的用户。

  1. 打开 Graph.java 并将以下函数添加到 Graph 类。

    public static UserCollectionResponse getUsers() throws Exception {
        // Ensure client isn't null
        if (_appClient == null) {
            throw new Exception("Graph has not been initialized for app-only auth");
        }
    
        return _appClient.users().get(requestConfig -> {
            requestConfig.queryParameters.select = new String[] { "displayName", "id", "mail" };
            requestConfig.queryParameters.top = 25;
            requestConfig.queryParameters.orderby = new String[] { "displayName" };
        });
    }
    
  2. App.java 中的空listUsers函数替换为以下内容。

    private static void listUsers() {
        try {
            final UserCollectionResponse users = Graph.getUsers();
    
            // Output each user's details
            for (User user: users.getValue()) {
                System.out.println("User: " + user.getDisplayName());
                System.out.println("  ID: " + user.getId());
                System.out.println("  Email: " + user.getMail());
            }
    
            final Boolean moreUsersAvailable = users.getOdataNextLink() != null;
            System.out.println("\nMore users available? " + moreUsersAvailable);
        } catch (Exception e) {
            System.out.println("Error getting users");
            System.out.println(e.getMessage());
        }
    }
    
  3. 运行应用,登录并选择选项 4 以列出用户。

    Please choose one of the following options:
    0. Exit
    1. Display access token
    2. List users
    3. Make a Graph call
    2
    User: Adele Vance
      ID: 05fb57bf-2653-4396-846d-2f210a91d9cf
      Email: AdeleV@contoso.com
    User: Alex Wilber
      ID: a36fe267-a437-4d24-b39e-7344774d606c
      Email: AlexW@contoso.com
    User: Allan Deyoung
      ID: 54cebbaa-2c56-47ec-b878-c8ff309746b0
      Email: AllanD@contoso.com
    User: Bianca Pisani
      ID: 9a7dcbd0-72f0-48a9-a9fa-03cd46641d49
      Email: NO EMAIL
    User: Brian Johnson (TAILSPIN)
      ID: a8989e40-be57-4c2e-bf0b-7cdc471e9cc4
      Email: BrianJ@contoso.com
    
    ...
    
    More users available? True
    

代码说明

请考虑 函数中的 getUsers 代码。

访问集合

此方法返回用户的集合。 Microsoft Graph 中返回集合的大多数 API 不会在单个响应中返回所有可用结果。 相反,它们使用 分页 返回部分结果,同时为客户端提供请求下一页的方法。

默认页面大小

使用分页的 API 实现默认页面大小。 对于用户,默认值为 10。 客户端可以使用 $top 查询参数请求更多 (或更少的 ) 。 在 getUsers中,使用请求配置中的 属性完成top添加$top

注意

top 设置的值是上限,而不是显式数字。 API 返回指定值 内的用户 数。

获取后续页面

如果服务器上有更多可用的结果,则集合响应将包含一个 @odata.nextLink 具有 API URL 的属性,用于访问下一页。 Java 客户端库针对集合响应对象提供 getOdataNextLink 方法。 如果此方法返回非 null,则有更多可用的结果。

集合排序

函数使用 orderBy 请求配置上的 属性来请求按用户的显示名称排序的结果。 此属性将 $orderby 查询参数 添加到 API 调用。

后续步骤