应用场景#
web应用通过QQ登录授权实现第三方登录
操作步骤#
- 首先要有一个自己可以访问的网址.(www.xxx.com).
- 然后在QQ互联平台验证域名信息,设置回调地址.如:http://graph.qq.com/demo/index.jsp
- 获取AppId,AppKey进行开发
具体实现方式#
登录按钮##
将请求的路径写入a标签中
<a href="https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=*****&redirect_uri=*****&state=*****&scope=get_user_info,getinfo">
打*号指的是都要自己填写
- client_id是AppId
- redirect_uri是回调的方法
- state是用于校验的参数,是由自己制定的密钥,在回调的方法里会一同返回.
回调方法##
- 点击登录按钮,登录完成后,会再一次进行跳转,跳转路径如:http://graph.qq.com/demo/index.jsp?code=9A5F************************06AF&state=1
- 这样就可以在回调方法中可以获取该code,并用于下一步的验证
StringBuffer callBackUrl = request.getRequestURL();
String code = request.getParameter("code");//得到回调请求所带的参数
String dialog_url="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id="+qq_app_id+"&redirect_uri="+callBackUrl+"&state=1&client_secret="+qq_app_key+"&code="+code;//使用code发起新的请求
String apiResult = getApiResult(dialog_url);
//如果成功返回,即可在返回包中获取到Access Token
//如:apiResult = "access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14"
String access_token = apiResult.substring(apiResult.indexOf("=")+1, apiResult.indexOf("&"));//字符串分割得到access_token
String refresh_token = apiResult.substring(apiResult.lastIndexOf("=")+1);//字符串分割得到refresh_token
- 已经获取了access_token,就可以以此获取openId,每个qq用户的openId都是唯一的.
String dialog_url2 = "https://graph.qq.com/oauth2.0/me?access_token="+access_token;
String apiResult = getApiResult(dialog_url2);//返回值如下:allback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
String jsonStr = apiResult.substring(apiResult.indexOf("(")+1, apiResult.indexOf(")"));//截取字符串
JSONObject jo = JSONObject.fromObject(jsonStr);//用net.sf.json.JSONObject对该字符串进行解析
String openId = jo.getString("openid");//获取其中的openId
- 最后,用openId获取用户的信息吧
String dialog_url3 = "https://graph.qq.com/user/get_user_info?access_token="+access_token+"&oauth_consumer_key="+qq_app_id+"&openid="+openId;
String apiResult = getApiResult(dialog_url3);
//返回的参数
//以json形式返回{"ret":0,"msg":"","nickname":"YOUR_NICK_NAME",...},通过解析就可得到想要的参数
- 这是我抽象出来的getApiResult方法
public String getApiResult(String url) throws IOException{
URL apiUrl = new URL(url);
URLConnection conn= apiUrl.openConnection();
InputStream in = conn.getInputStream();
String result = IOUtils.toString(in);
return result;
}