简体   繁体   English

Android - 如何获取谷歌加访问令牌?

[英]Android - how to get google plus access token?

Hello i am getting google plus access token without using OAuth 2.0 client ID with scopes. 您好我得到谷歌加访问令牌而不使用带范围的OAuth 2.0客户端ID。 But with this access token does not fetch email address. 但是使用此访问令牌不会获取电子邮件地址。 How to fetch user email address? 如何获取用户电子邮件地址?

Is there any difference between accesstoken with and without OAuth 2.0 client ID? 使用和不使用OAuth 2.0客户端ID的accesstoken之间有什么区别吗?

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();
                    }

There are 2 simple ways to get user Email from Google plus, 有两种简单的方法可以从Google Plus获取用户电子邮件,

1.Through Plus.AccountApi.getAccountName like below, 1.通过Plus.AccountApi.getAccountName如下,

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

2.Through plus.profile.emails.read scope and REST end point like 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 AccessToken from GooglePlus like below, 您需要通过" https://www.googleapis.com/auth/plus.profile.emails.read"此范围从GooglePlus获取AccessToken ,如下所示,

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.xml to use these methods. 您必须在AndroidManifest.xml声明权限<uses-permission android:name="android.permission.GET_ACCOUNTS" />才能使用这些方法。

Full Example from Google Developer site, Google开发者网站的完整示例,

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

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM