do-while 适合分页 api:先取第一页获总页数或下一页标识,再循环至无下一页;比 while 更自然,因至少请求一次;需先明确分页机制——页码型(如 page/total_pages)或游标型。

用 do-while 处理分页 API 的核心在于:先执行一次请求获取第一页和总页数(或下一页标识),再循环直到没有下一页为止。它比 while 更自然——因为至少要取第一页,无需预先判断条件。
明确分页机制类型再设计循环条件
第三方 API 分页方式不同,do-while 的退出逻辑也不同:
-
基于页码(page/totalPages):响应含
"page": 1, "total_pages": 5→ 循环条件为currentPage -
基于游标(cursor/next_cursor):响应含
"next_cursor": "abc123",末页为null或空字符串 → 循环条件为nextCursor != null && !nextCursor.isEmpty() -
基于链接(Link header):HTTP 响应头含
Link: <https:>; rel="next"</https:>→ 提取并判断 next 链接是否存在
do-while 循环体中完成三件事
每次迭代必须做且仅做这三步,避免重复请求或漏页:
- 发起请求:用当前页码或游标构造 URL,发送 HTTP 请求(如用 OkHttp 或 Spring RestTemplate)
-
解析并收集数据:提取响应中的业务数据列表(如
items字段),添加到全局List<t></t>中 -
更新分页状态:从响应中提取下一页参数(如
nextPage = resp.getPage() + 1或nextCursor = resp.getNextCursor())
注意异常与边界情况处理
真实场景中网络、限流、数据格式错误很常见,不能让一次失败中断整个抓取:
- 在循环内
try-catch网络异常(如IOException、SocketTimeoutException),记录日志后continue或按策略重试(如指数退避) - 检查 HTTP 状态码,对
429 Too Many Requests主动 sleep 并重试,对401/403立即终止并报错 - 解析 JSON 时捕获
JsonProcessingException,打印原始响应体便于排查字段变更 - 设置最大重试次数和总超时时间(例如最多翻 100 页,总耗时不超过 10 分钟),防无限循环
一个简洁可运行的游标分页示例
假设 API 返回 JSON:{"data":[...],"next_cursor":"xyz789"}
String nextCursor = null;
List<item> allItems = new ArrayList();
do {
String url = "https://api.example.com/items" + (nextCursor == null ? "" : "?cursor=" + nextCursor);
try {
ApiResponse response = httpClient.get(url, ApiResponse.class);
allItems.addAll(response.getData());
nextCursor = response.getNextCursor();
} catch (IOException e) {
log.error("请求失败,跳过当前页", e);
break; // 或 continue + 重试逻辑
}
} while (nextCursor != null && !nextCursor.trim().isEmpty());
</item>
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











