调用Google Drive v3接口查询目录文件仅返回100条是什么原因?
问题成因
Google Drive API v3的files.list接口默认采用分页机制返回数据,单页默认返回的最大文件数量为100条。你的代码仅请求了第一页数据,因此最多只能拿到100个文件条目,和文件夹实际文件数量无关。
补充说明:接口提供pageSize参数可调整单页返回条数,最大可设置为1000,超过1000条的场景必须通过分页逻辑拉取全量数据。
可行实现方案
方案1:单页拉取(适用于文件夹内文件数≤1000的场景)
直接在原请求URL中添加pageSize参数,将单页返回上限调整为1000即可,修改后的请求URL示例:https://www.googleapis.com/drive/v3/files?q=%271RpFcoEWYsRt2MX7FotKcLICqYq6l5MFY%27+in+parents&pageSize=1000&key=myKey方案2:分页循环拉取(适用于所有场景,无文件数量限制)
每次请求后判断返回结果中是否存在nextPageToken字段,存在则携带该token发起下一页请求,直到无nextPageToken返回即拉取完全部文件,参考实现代码如下:new Thread(() -> { String baseUrl = "https://www.googleapis.com/drive/v3/files?q=%271RpFcoEWYsRt2MX7FotKcLICqYq6l5MFY%27+in+parents&pageSize=1000&key=myKey"; String nextPageToken = null; AtomicInteger counter = new AtomicInteger(0); try { do { // 拼接分页token String requestUrl = baseUrl; if (nextPageToken != null) { requestUrl += "&pageToken=" + URLEncoder.encode(nextPageToken, StandardCharsets.UTF_8.name()); } URL url = new URL(requestUrl); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.connect(); JsonParser jp = new JsonParser(); JsonElement root = jp.parse(new InputStreamReader((InputStream) urlConnection.getContent())); JsonObject rootObj = root.getAsJsonObject(); JsonArray files = rootObj.get("files").getAsJsonArray(); for (JsonElement file : files) { String n = file.getAsJsonObject().get("name").getAsString(); Log.e("amt", counter.getAndIncrement() + ""); // 原有过滤逻辑保留即可 //if (n.toLowerCase().contains(name.toLowerCase())) ret.add(n); } // 读取下一页token,没有则为null退出循环 nextPageToken = rootObj.has("nextPageToken") ? rootObj.get("nextPageToken").getAsString() : null; urlConnection.disconnect(); } while (nextPageToken != null); } catch (Exception e) { e.printStackTrace(); } }).start();
内容的提问来源于stack exchange,提问作者SprintKeyz
相关产品推荐
相关产品推荐

