经过一番研究,我得到了关注。
ID token 用于验证用户的真实性,access token 用于获知用户即将登录的e-mail id 信息。 Access token 的获取方式与 id token 相同,如下所示。
oAuthscopes = "oauth2:"+"https://www.googleapis.com/auth/userinfo.email"+" "+"https://www.googleapis.com/auth/plus.login";
protected String fetchAccessToken() throws IOException{
try {
return GoogleAuthUtil.getToken(act, email, oAuthscopes);
}
catch(GooglePlayServicesAvailabilityException e){
act.handleException(e);
}
catch(UserRecoverableAuthException e){
act.handleException(e);
}
catch (GoogleAuthException e) {
e.printStackTrace();
}
return null;
}
注意 oAtuthScopes 的作用。您可以根据应用程序的需要指定任意数量的带空格的范围,以向用户请求权限。
现在,要从这些范围内获取用户信息,请执行以下操作。
URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token="+accessToken);
StringBuffer val = returnJson(url);
url = new URL("https://www.googleapis.com/oauth2/v1/tokeninfo?alt=json&id_token="+idToken);
StringBuffer valVerify = returnJson(url);
方法returnjSon(URL)是
StringBuffer returnJson(URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream iStream = conn.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(iStream));
String line;
StringBuffer val = new StringBuffer();
while((line = read.readLine())!=null){
val.append(line);
}
return val;
}
访问令牌将返回类似,
{ "id": "10271045940xxxxxx", "email": "xxxx",
"verified_email": true, "name": "XXXX", "given_name": "XXXX",
“family_name”:“XXXX”,“链接”:“https://plus.google.com/+XXXX”,
“图片”:“https://lh4.googleusercontent.com/xxxx”,“性别”:“男性”,“地区”:“XX”}
id 令牌会返回类似的东西。您可以在 logcat 中打印以进行预览。
然后,
JSONObject reader = new JSONObject(val.toString());
String email = (String)reader.get("email"));
String name = (String)reader.get("name"));
reader = new JSONObject(valVerify.toString());
boolean verified = reader.getBoolean("email_verified"));