我用 Apache 的 HttpClient 制作的。这是我的解决方案,非常适合我。
首先指向授权url:
https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email&state=%2Fprofile&response_type=code&client_id=<YOUR_CLIENT_ID>&redirect_uri=<YOUR_CALLBACK_URL>
然后从您的获取参数redirect_uri
并构建请求正文以获取access_token
:
String code = request.getParameter("code");
String foros = "code="+code +
"&client_id=<YOUR_CLIENT_ID>" +
"&client_secret=<YOUR_CLIENT_SECRET>" +
"&redirect_uri="+getText("google.auth.redirect.uri") +
"&grant_type=authorization_code";
然后使用 HttpClient 进行 POST 并使用简单的 JSON 解析器解析出访问令牌。
HttpClient client = new HttpClient();
String url = "https://accounts.google.com/o/oauth2/token";
PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
try {
post.setRequestEntity(new StringRequestEntity(foros, null, null));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
String accessToken = null;
try {
client.executeMethod(post);
String resp = post.getResponseBodyAsString();
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(resp);
JSONObject parsed = (JSONObject)obj;
accessToken = (String) parsed.get("access_token");
} catch (HttpException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
throw new RuntimeException(e);
}
现在您有了访问令牌,您现在可以访问所有Google API。例如,获取所有用户信息:
GetMethod getUserInfo = new GetMethod("https://www.googleapis.com/oauth2/v1/userinfo?access_token="+accessToken);
String googleId = null;
String email = null;
String name = null;
String firstName = null;
String lastName = null;
try {
client.executeMethod(getUserInfo);
String resp = getUserInfo.getResponseBodyAsString();
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(resp);
JSONObject parsed = (JSONObject)obj;
googleId = (String) parsed.get("id");
email = (String) parsed.get("email");
name = (String) parsed.get("name");
firstName = (String) parsed.get("given_name");
lastName = (String) parsed.get("family_name");
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
throw new RuntimeException(e);
}
您现在可以保存这些数据并将其用于登录您的应用程序。