如何在Google Apps转销商API中使用nextPageToken?

时间:2015-06-16 08:23:33

标签: google-api google-admin-sdk google-reseller-api

我正在编写一个简单的Java应用程序,使用Reseller API从Google Apps经销商处获取所有客户订阅。但是,由于每页最大大小为100,我无法查看结果,我无法找出下一页令牌。这是迄今为止的代码。如何使用setNextPageToken()并打印所有结果?

public static void main(String[] args) throws IOException {
        GoogleCredential credentials = GoogleApiUtil.getCredentials();

        Reseller service = new Reseller.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials)
                .setApplicationName("ResellerDemo").build();


        boolean allResultsRead = false;
        String nextPageToken = null;
        while (!allResultsRead) {
            Subscriptions result = service.subscriptions().list()   
                    .execute();
            List<Subscription> subscriptions = result.getSubscriptions();
            nextPageToken = result.getNextPageToken();
            if (subscriptions == null || subscriptions.size() == 0) {
                System.out.println("No subscriptions found.");
            } else {
                System.out.println("Subscriptions:");
                for (Subscription sub : subscriptions) {
                    System.out.printf("%s (%s, %s)\n",
                            sub.getCustomerId(),
                            sub.getSkuId(),                               
                            sub.getPlan().getCommitmentInterval());
                }
            }
            if (result.getNextPageToken() == null) {
                allResultsRead = true;

            } else {
                result.setNextPageToken(result.getNextPageToken());

            }

        }

1 个答案:

答案 0 :(得分:1)

这应该有效。当你实现真实的东西时,请确保你以指数退避重试。

public void retrieveAll() throws IOException, InterruptedException {

    GoogleCredential credentials = GoogleApiUtil.getCredentials();

    Reseller service = new Reseller.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials)
            .setApplicationName("ResellerDemo").build();

    String nextPageToken = null;


    do {
        Subscriptions subsList = service.subscriptions().list().setMaxResults(Long.valueOf(100)).setPageToken(nextPageToken)
                .execute();
        printSubscirptions(subsList);

        nextPageToken = subsList.getNextPageToken();

    } while(nextPageToken != null && !"".equals(nextPageToken));


}

private void printSubscirptions(Subscriptions subscriptions){
    System.out.println("Subscriptions:");
    for (Subscription sub : subscriptions.getSubscriptions()) {
        System.out.printf("%s (%s, %s)\n",
                sub.getCustomerId(),
                sub.getSkuId(),
                sub.getPlan().getCommitmentInterval());
    }

}