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

4.5k Views Asked by At

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?

2

There are 2 best solutions below

0
daniel.comsa On
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);
    };
}
1
Andreas On

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