0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Google API Client Libraries] APIを使用してRead timed out(java.net.SocketTimeoutException)が発生した場合の対処方法

Posted at

Google Sheets APIを使用していて「Read time out」のエラーが発生しました。

Exception in thread "main" java.net.SocketTimeoutException: Read timed out
	at java.base/sun.nio.ch.NioSocketImpl.timedRead(NioSocketImpl.java:278)
	at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:304)
	at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:346)
	at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:796)
	at java.base/java.net.Socket$SocketInputStream.read(Socket.java:1099)

スプレットシートのデータ量が膨大になってしまったのが原因です。
time outを変えずになんとかロジックで逃げようとしましたが、
限界を迎えたのでtime outを変えることにしました。

private static HttpRequestInitializer setHttpTimeout(HttpRequestInitializer requestInitializer) {
    return new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest httpRequest) throws IOException {
            requestInitializer.initialize(httpRequest);
            httpRequest.setConnectTimeout(5 * 60000);
            httpRequest.setReadTimeout(5 * 60000);
        }
    };
}

HttpRequestInitializerを取得しているところに追加してください。

スプレットシートAPIの場合は
⧉[Google Sheets API] JavaでスプレットシートのメニューとAPIを関連づけてみた(2.2. Sheetsインスタンスの取得)
を参照ください。
スプレットシートAPIでなくとも同じです。

public static Spreadsheets getSpreadsheets() throws IOException, GeneralSecurityException {
    InputStream input = new FileInputStream("/** サービスアカウントキーのファイルパス */");
    GoogleCredentials credential = ServiceAccountCredentials.fromStream(input).createScoped(Arrays.asList(SheetsScopes.SPREADSHEETS));

    HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = GsonFactory.getDefaultInstance();

    //ここを変更
    HttpRequestInitializer httpRequestInitializer = setHttpTimeout(new HttpCredentialsAdapter(credential));
//   HttpRequestInitializer httpRequestInitializer = new HttpCredentialsAdapter(credential);

    Sheets service = new Sheets.Builder(transport,jsonFactory,httpRequestInitializer).build();
    
    return service.spreadsheets();
}

なお、設定可能なタイムアウトは下記2つです。

ConnectTimeout
サーバーへ接続要求を送信し、接続確立のレスポンスを受け取るまで待機する時間

ReadTimeout
サーバーへの接続確立後、実行したAPIのレスポンスを受け取るまで待機する時間

おしまい。。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?