Android - 如何获得 google plus 访问令牌?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23759529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:25:12  来源:igfitidea点击:

Android - how to get google plus access token?

androidoauth-2.0google-playaccess-token

提问by Mind Android

Hello i am getting google plus access token without using OAuth 2.0 client ID with scopes. But with this access token does not fetch email address. How to fetch user email address?

您好,我在不使用 OAuth 2.0 客户端 ID 的情况下获得了 google plus 访问令牌。但是使用此访问令牌不会获取电子邮件地址。如何获取用户电子邮件地址?

Is there any difference between accesstoken with and without OAuth 2.0 client ID?

带和不带 OAuth 2.0 客户端 ID 的访问令牌有什么区别吗?

I have used following code,

我使用了以下代码,

String accessToken="";
                    try {
                        accessToken = GoogleAuthUtil.getToken(
                                getApplicationContext(),
                                mPlusClient.getAccountName(), "oauth2:"
                                        + Scopes.PLUS_LOGIN + " "
                                        + Scopes.PLUS_PROFILE);

                        System.out.println("Access token==" + accessToken);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

采纳答案by Mind Android

String accessToken = "";
try {
  URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo");
  // get Access Token with Scopes.PLUS_PROFILE
  String sAccessToken;
  sAccessToken = GoogleAuthUtil.getToken(
    LoginCheckActivity.this,
    mPlusClient.getAccountName() + "",
    "oauth2:"
      + Scopes.PLUS_PROFILE + " "
      + "https://www.googleapis.com/auth/plus.login" + " "
      + "https://www.googleapis.com/auth/plus.profile.emails.read");
} catch (UserRecoverableAuthException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();                  
  Intent recover = e.getIntent();
  startActivityForResult(recover, 125);
  return "";
} catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
} catch (GoogleAuthException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

回答by Spring Breaker

There are 2 simple ways to get user Email from Google plus,

有两种简单的方法可以从 Google plus 获取用户电子邮件,

1.Through Plus.AccountApi.getAccountNamelike below,

1.通过Plus.AccountApi.getAccountName如下,

String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

2.Through plus.profile.emails.read scope and REST end pointlike below,

2.通过plus.profile.emails.read scope and REST end point如下,

Get the GooglePlus AccessToken

获取 GooglePlus AccessToken

You need to pass " https://www.googleapis.com/auth/plus.profile.emails.read"this scope to get the AccessTokenfrom GooglePlus like below,

您需要传递" https://www.googleapis.com/auth/plus.profile.emails.read"此范围才能AccessToken从 GooglePlus获取如下内容,

accessToken = GoogleAuthUtil.getToken(
                                getApplicationContext(),
                                mPlusClient.getAccountName(), "oauth2:"
                                        + Scopes.PLUS_LOGIN + " "
                                        + Scopes.PLUS_PROFILE+" https://www.googleapis.com/auth/plus.profile.emails.read");

Make a REST call to the endpoint and do simple JSON parsing

对端点进行 REST 调用并进行简单的 JSON 解析

https://www.googleapis.com/plus/v1/people/me?access_token=XXXXXXXXXXXXX

https://www.googleapis.com/plus/v1/people/me?access_token=XXXXXXXXXXXXX

You must declare the permission <uses-permission android:name="android.permission.GET_ACCOUNTS" />in your AndroidManifest.xmlto use these methods.

您必须声明允许<uses-permission android:name="android.permission.GET_ACCOUNTS" />AndroidManifest.xml使用这些方法。

Full Example from Google Developer site,

来自谷歌开发者网站的完整示例,

Do something like below to retrieve the authenticated user's Email from Google plus,

执行以下操作以从 Google plus 检索经过身份验证的用户的电子邮件,

class UserInfo {
  String id;
  String email;
  String verified_email;
}

final String account = Plus.AccountApi.getAccountName(mGoogleApiClient);

AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {

  @Override
  protected UserInfo doInBackground(Void... params) {
    HttpURLConnection urlConnection = null;

    try {
      URL url = new URL("https://www.googleapis.com/plus/v1/people/me");
      String sAccessToken = GoogleAuthUtil.getToken(EmailTest.this, account,
        "oauth2:" + Scopes.PLUS_LOGIN + " https://www.googleapis.com/auth/plus.profile.emails.read");

      urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.setRequestProperty("Authorization", "Bearer " + sAccessToken);

      String content = CharStreams.toString(new InputStreamReader(urlConnection.getInputStream(),
          Charsets.UTF_8));

      if (!TextUtils.isEmpty(content)) {
        JSONArray emailArray =  new JSONObject(content).getJSONArray("emails");

        for (int i = 0; i < emailArray.length; i++) {
          JSONObject obj = (JSONObject)emailArray.get(i);

          // Find and return the primary email associated with the account
          if (obj.getString("type") == "account") {
            return obj.getString("value");
          }
        }
      }
    } catch (UserRecoverableAuthException userAuthEx) {
      // Start the user recoverable action using the intent returned by
      // getIntent()
      startActivityForResult(userAuthEx.getIntent(), RC_SIGN_IN);
      return;
   } catch (Exception e) {
      // Handle error
      // e.printStackTrace(); // Uncomment if needed during debugging.
    } finally {
      if (urlConnection != null) {
        urlConnection.disconnect();
      }
    }

    return null;
  }

  @Override
  protected void onPostExecute(String info) {
      // Store or use the user's email address
  }

};

task.execute();

Fore more info read this

欲了解更多信息,请阅读本文

https://developers.google.com/+/mobile/android/people

https://developers.google.com/+/mobile/android/people