实现QQ登陆(QQ互联)

更多干货

项目需要做QQ、微博等登陆第三方的功能,第一次接触,虽然官网上有sdk,接口写的很好,调用即可,但是没有文档,看着头疼就自己写了

  步骤不多说:

  一、申请AppID和AppKey,申请地址:点击打开链接,说明 里面需要域名公安备案号,如果只是自己练手就随便写,审核虽然不通过但是也会给你AppId和AppKey,可以用自己的QQ进行登陆操作。

二、在登陆界面引入QQ登陆图标,按钮链接里面就是请求地址,填上自己的appId和回调地址即可

<a href="https://graph.qq.com/oauth/show?which=Login&display=pc&response_type=code&client_id=???&redirect_uri=???&scope=scope"
            class="icon connect-qq"><img src="${ctx}/images/Connect_logo_7.png"/></a>

三、点击登陆链接后会跳转到QQ授权登陆界面,如果用户确认登陆,就会跳转到回调地址,并且返回一个code值;

四、接下来就是oAuth2协议里面写的了,通过这个code值去获取QQ用户的access_token,通过access_token再置换用户的Open_Id,通过Open_Id再去获取用户信息。把里面自己的appid和Appkey填上就行了,我里面封装了一个通过url去请求数据的方法httpRequest();

    

public String QQLogin( String code ,HttpServletRequest request, HttpServletResponse response) throws BizException {
       //填写Appid,appkey和回调地址
        String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&
         client_id=???&client_secret=???&redirect_uri=???&code=" + code;
        String responseStr = httpRequest(url);
 
       //获取access_Token
        String tokens[] = responseStr.split("&");
        String token = tokens[0];
        String userUrl = "https://graph.qq.com/oauth2.0/me?" + token;
        String sr = httpRequest(userUrl);
        JSONObject result = JSON.parseObject(sr.substring(10, sr.length() - 3));
 
        //获取Open_ID
        String openId = (String) result.get("openid");
      //根据OpenId去获取用户信息
        String userinfoUrl = "https://graph.qq.com/user/get_user_info?" + token +
                    "&oauth_consumer_key=appId&openid=" + openId;
            String userInfoText = httpRequest(userinfoUrl);
            JSONObject userInfoResult = JSON.parseObject(userInfoText);
            String nickName = (String) userInfoResult.get("nickname");
            String userIconUrl = (String) userInfoResult.get("figureurl");
           
        }
    return null;
}
 
    //http请求,链接url
    public static String httpRequest(String url) {
        HttpURLConnection urlConnection = null;
        String responseStr = "";
        try {
            urlConnection = (HttpURLConnection) new URL(url).openConnection();
            urlConnection.setRequestProperty("Accept-Charset", "utf-8");
            urlConnection.setRequestProperty("contentType", "utf-8");
            urlConnection.connect();
            InputStream inputStream = urlConnection.getInputStream();
            responseStr = StreamToString.ConvertToString(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseStr;
    }

猜你喜欢

转载自blog.csdn.net/qq_27384769/article/details/82227368