1

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?

Elad Benda2
  • 13,852
  • 29
  • 82
  • 157

2 Answers2

3

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
        }
    };
}
Andreas
  • 326
  • 2
  • 5
  • On python I just increased the amount of retries to `10` instead of the default `1` as a quick solution which seemed to have resolved my connection errors on a slower connection. ```service = build("sheets", "v4", credentials=credentials, num_retries=10) sheet = service.spreadsheets()``` – Francois Jul 07 '23 at 12:21
-1
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);
    };
}