3

我有一个 Java 应用程序需要让用户授权我的应用程序访问 Google 服务。我有以下代码来显示和获得我需要的授权:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JsonFactory, clientSecrets, scopes).build();
Credential cred = null; 
try
  {
    LocalServerReceiver localSrv = new LocalServerReceiver();

    AuthorizationCodeInstalledApp app = new AuthorizationCodeInstalledApp(flow, localSrv);

    cred = app.authorize(userName);
  }
  catch(Exception ex)
  {
    ex.printStackTrace();
  }
    refreshToken = cred.getRefreshToken();

如果用户单击“授权”或“取消”按钮,一切都很好。但是,如果他们关闭浏览器窗口,整个应用程序就会冻结。有没有办法处理这种情况以防止冻结或引入超时?

4

1 回答 1

1

我们还将 Google Drive 集成到我们的应用程序中,这是我关心的问题。发生的情况是,如果您调用该authorize()方法,则调用所在的任何线程都会阻塞。您会注意到,当授权窗口打开时,应用程序也没有响应。

我希望有一种方法可以检测用户是否关闭了授权窗口,但这似乎只会导致LocalServerReceiver无休止地等待一个永远不会到达的令牌。

此时最好的选择是异步调用authorize(),并等待响应。

编辑:我看了看LocalServerReceiver源代码,因为我们希望接收者重定向到不同的 URL,而不是显示纯文本。它实现了VerificationCodeReceiver具有阻塞waitForCode()方法的接口。似乎有必要AuthorizationCodeInstalledApp.authorize()在等待时阻止,即使您自己实现VerificationCodeReceiver.

于 2016-07-20T08:12:00.190 回答