Elad Benda2
Elad Benda2

Reputation: 15442

how to set timeout for: `google-client spreadsheet api`?

I'm using google-client api for spreadsheet.

I get a time out after 20 seconds. How can i set the timeout to a custom value?

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();
}

should i set it in the HttpTransport?

Upvotes: 2

Views: 5129

Answers (2)

Andreas
Andreas

Reputation: 326

I ran into the same issue and actually found a documented solution from Google

Google API Client Libraries - Timeouts and Errors

And for simplicity your implementation must add a call to:

.setHttpRequestInitializer(createHttpRequestInitializer(credential))

In the Sheets.Builder and then add the following method to your class, provide any timeout values seems reasonable for the application.

    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
        }
    };
}

Upvotes: 3

daniel.comsa
daniel.comsa

Reputation: 19

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);
    };
}

Upvotes: 0

Related Questions