如何在Google Apps Reseller API中使用nextPageToken



我正在编写一个简单的Java应用程序,该应用程序使用经销商API从Google Apps Reseller获取所有客户订阅。但是,我无法对结果进行分页,因为最大大小为每页 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());
            }
        }

这应该有效。当您实现实际操作时,请确保使用指数退避重试。

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

相关内容

  • 没有找到相关文章

最新更新