在Android上为Gmail API设置连接超时

时间:2018-10-11 10:31:31

标签: java android timeout gmail-api

我正在使用此not so well documented Gmail API在Android Studio上代表用户发送电子邮件。除发送超时外,其他一切正常。当发送请求失败时,按原样使用它会抛出IOException: NetworkError,但是抛出它会花费太多时间(我猜是5分钟或更长时间,没有计算出来)。我要自定义它。

我找到了this,但是没有用。

这是我的代码:

public Message send() {

   GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
        getApplicationContext(), GMAIL_SCOPES)
        .setBackOff(new ExponentialBackOff())
        .setSelectedAccountName(account);

   JsonFactory jsonFactory = new JacksonFactory();
   HttpTransport httpTransport = new NetHttpTransport();

   service = new Gmail.Builder(httpTransport, jsonFactory, 
                              setHttpTimeout(credential))
                     .setApplicationName("My app")
                     .build();

   try {
      Message message = createMessageWithEmail();
      return service.users()
                    .messages()
                    .send(credential.getSelectedAccountName(), message)
                    .execute();

   } catch (UserRecoverableAuthIOException e) {
       listener.onRequirePermission(e.getIntent());
       requiringPermission = true;
   } catch (MessagingException e) {
       e.printStackTrace();
   } catch (IOException e) {
       e.printStackTrace();
   }
      return null;
}

private HttpRequestInitializer setHttpTimeout(final HttpRequestInitializer 
                                             requestInitializer) {
   return httpRequest -> {
      requestInitializer.initialize(httpRequest);
      httpRequest.setConnectTimeout(SEND_TIMEOUT);
      httpRequest.setReadTimeout(READ_TIMEOUT);
   };
}

也欢迎使用setConnectTimeout()以外的其他方式。

0 个答案:

没有答案