我有一个驱动器应用程序,它请求所有未丢弃的文件。但有时它会引发读取超时的 IOexception。有没有办法避免这种情况?
这是我得到的错误:
发生错误:java.net.SocketTimeoutException:读取超时
也许我的指数退避实施错误。
这是我用来获取文件的代码:
private static List<File> retrieveAllNoTrashFiles(Drive service) throws IOException, InterruptedException {
List<File> result = new ArrayList<File>();
Files.List request = service.files().list().setQ("trashed = false").setMaxResults(1000);
do {
try {
FileList files =executeRequest(service,request);
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) { //here I sometimes get the read timeout
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null
&& request.getPageToken().length() > 0);
return result;
}
private static FileList executeRequest(Drive service,Files.List request) throws IOException, InterruptedException {
Random randomGenerator = new Random();
for (int n = 0; n < 5; ++n) {
try {
return(request.execute());
} catch (GoogleJsonResponseException e) {
if (e.getDetails().getCode() == 403
&& (e.getDetails().getErrors().get(0).getReason().equals("rateLimitExceeded")
|| e.getDetails().getErrors().get(0).getReason().equals("userRateLimitExceeded"))) {
// Apply exponential backoff.
Thread.sleep((1 << n) * 1000 + randomGenerator.nextInt(1001));
}
//else {
// Other error, re-throw.
// throw e;
// }
}
}catch(SocketTimeoutException e){
Thread.sleep((1 << n) * 1000 + randomGenerator.nextInt(1001));
}
System.err.println("There has been an error, the request never succeeded.");
return null;
}