- // Send our HTTP request to the directory server.
- URLConnection link =
- new URL(HOST_LIST_PATH + JniInterface.nativeGetApiKey()).openConnection();
- link.addRequestProperty("client_id", JniInterface.nativeGetClientId());
- link.addRequestProperty("client_secret", JniInterface.nativeGetClientSecret());
- link.setRequestProperty("Authorization", "OAuth " + authToken);
-
- // Listen for the server to respond.
- StringBuilder response = new StringBuilder();
- Scanner incoming = new Scanner(link.getInputStream());
- Log.i("auth", "Successfully authenticated to directory server");
- while (incoming.hasNext()) {
- response.append(incoming.nextLine());
- }
- incoming.close();
-
- // Interpret what the directory server told us.
- JSONObject data = new JSONObject(String.valueOf(response)).getJSONObject("data");
- mHosts = data.getJSONArray("items");
- Log.i("hostlist", "Received host listing from directory server");
- } catch (RuntimeException ex) {
- // Make sure any other failure is reported to the user (as an unknown error).
- throw ex;
- } catch (Exception ex) {
- // Assemble error message to display to the user.
- String explanation = getString(R.string.error_unknown);
- if (ex instanceof OperationCanceledException) {
- explanation = getString(R.string.error_auth_canceled);
- } else if (ex instanceof AuthenticatorException) {
- explanation = getString(R.string.error_no_accounts);
- } else if (ex instanceof IOException) {
- if (!mAlreadyTried) {
- // This was our first connection attempt.
-
- synchronized (mLock) {
- if (mAccount != null) {
- // We got an account, but couldn't log into it. We'll retry in case
- // the system's cached authentication token had already expired.
- AccountManager authenticator = AccountManager.get(mUi);
- mAlreadyTried = true;
-
- Log.w("auth", "Requesting renewal of rejected auth token");
- authenticator.invalidateAuthToken(mAccount.type, mToken);
- mToken = null;
- authenticator.getAuthToken(
- mAccount, TOKEN_SCOPE, null, mUi, this, mNetwork);
-
- // We're not in an error state *yet*.
- return;
- }
- }
-
- // We didn't even get an account, so the auth server is likely unreachable.
- explanation = getString(R.string.error_bad_connection);
- } else {
- // Authentication truly failed.
- Log.e("auth", "Fresh auth token was also rejected");
- explanation = getString(R.string.error_auth_failed);
- }
- } else if (ex instanceof JSONException) {
- explanation = getString(R.string.error_unexpected_response);
- }