我有一个驱动器应用程序,它请求所有未删除的文件。但有时会抛出读取超时的IO异常。有办法避免这种情况吗?
这是我得到的错误:
发生错误: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;
}
几天前我也有同样的经历。我的问题的答案在这里找到了。https://code.google.com/p/google-api-java-client/wiki/FAQ。创建 Drive 实例时,您可以调用 setHttpRequestInitializer 方法,将 HttpRequestInitializer 的新实例作为参数传递,并实现初始化方法。在那里,您可以增加 ReadTimeout 和 ConnectionTimeout。
这是示例代码:
Drive drive = new Drive.Builder(this.httpTransport, this.jsonFactory, this.credential).setHttpRequestInitializer(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest httpRequest) throws IOException {
credential.initialize(httpRequest);
httpRequest.setConnectTimeout(300 * 60000); // 300 minutes connect timeout
httpRequest.setReadTimeout(300 * 60000); // 300 minutes read timeout
}
}).setApplicationName("My Application").build();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)