如何设置超时:“谷歌-客户端电子表格 API”



我正在使用谷歌客户端 API 进行电子表格。

我在 20 秒后超时。如何将超时设置为自定义值?

private Sheets initService(GoogleCredential credential) throws GeneralSecurityException, IOException {
    final HttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("my_app")
            .build();
}

我应该在HttpTransport中设置它吗?

我遇到了同样的问题,实际上从谷歌那里找到了一个记录的解决方案

谷歌 API 客户端库 - 超时和错误

为简单起见,您的实现必须添加对以下内容的调用:

.setHttpRequestInitializer(createHttpRequestInitializer(credential))

在 Sheets.Builder 中,然后将以下方法添加到您的类中,提供任何对于应用程序来说似乎合理的超时值。

    private HttpRequestInitializer createHttpRequestInitializer(final HttpRequestInitializer requestInitializer) {
    return new HttpRequestInitializer() {
        @Override
        public void initialize(final HttpRequest httpRequest) throws IOException {
            requestInitializer.initialize(httpRequest);
            httpRequest.setConnectTimeout(3 * 60000); // 3 minutes connect timeout
            httpRequest.setReadTimeout(3 * 60000); // 3 minutes read timeout
        }
    };
}
private Sheets initService(GoogleCredential credential) throws GeneralSecurityException, IOException {
    final HttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, setTimeout(credential, 60000))
        .setApplicationName("my_app")
        .build();
}
private HttpRequestInitializer setTimeout(final HttpRequestInitializer initializer, final int timeout) {
    return request -> {
        initializer.initialize(request);
        request.setReadTimeout(timeout);
    };
}

相关内容

  • 没有找到相关文章