日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

前期準備工作

1.云服務器

2.備案的域名

3.本地調試需要修改hosts文件,將域名映射到127.0.0.1

申請QQ互聯,并成為開發者

申請QQ互聯創建應用時需要備案域名,所以建議提前準備備案域名。

QQ互聯:https://connect.qq.com/index.html

登錄后,點擊頭像,進入認證頁面,填寫信息,等待審核。

 

Java如何實現QQ第三方登錄

 

審核通過后創建應用

 

Java如何實現QQ第三方登錄

 

應用創建通過審核后,就可以使用App ID 和 APP Key

 

Java如何實現QQ第三方登錄

 

前期工作就這些了,后面可以開始寫代碼了。

項目結構:

 

Java如何實現QQ第三方登錄

 

properties或者yml配置文件(這里就是簡單的配置了一下,可以自行添加數據庫等配置)

server.port=80server.servlet.context-path=/ #qq互聯qq.oauth.http:QQ互聯中申請填寫的網站地址

 

Java如何實現QQ第三方登錄

 

在pom中添加依賴

<!--httpclient--><dependency>    <groupId>org.Apache.httpcomponents</groupId>    <artifactId>httpclient</artifactId>    <version>4.5.6</version></dependency><!--阿里 JSON--><dependency>    <groupId>com.alibaba</groupId>    <artifactId>fastjson</artifactId>    <version>1.2.47</version></dependency>

發送QQ登錄請求

定義全局變量獲取配置文件中的網站地址

@Value("${qq.oauth.http}")private String http;

定義登錄回調地址(可以用網站地址拼接或者直接寫)

//QQ互聯中的回調地址String backUrl = http + "/index";

 

Java如何實現QQ第三方登錄

 

登錄請求方法代碼

@GetMapping("/qq/login")public String qq(HttpSession session) throws UnsupportedEncodingException {    //QQ互聯中的回調地址    String backUrl = http + "/index";     //用于第三方應用防止CSRF攻擊    String uuid = UUID.randomUUID().toString().replaceAll("-","");    session.setAttribute("state",uuid);     //Step1:獲取Authorization Code    String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code"+            "&client_id=" + QQHttpClient.APPID +            "&redirect_uri=" + URLEncoder.encode(backUrl, "utf-8") +            "&state=" + uuid;     return "redirect:" + url;}

正確返回示例:

JSON示例:

Content-type: text/html; charset=utf-8{"ret":0,"is_lost":0,"nickname":"Peter","gender":"男","country":"中國","province":"廣東","city":"深圳","figureurl":"http://imgcache.qq.com/qzone_v4/client/userinfo_icon/1236153759.gif","is_yellow_vip":1,"is_yellow_year_vip":1,"yellow_vip_level":7,"is_yellow_high_vip": 0}

錯誤返回示例

Content-type: text/html; charset=utf-8{"ret":1002,"msg":"請先登錄"}

用戶資料的接口文檔:https://wiki.open.qq.com/wiki/v3/user/get_info

請求成功,用戶確認登錄后回調方法

@GetMapping("/index")public String qqcallback(HttpServletRequest request, HttpServletResponse response) throws Exception {    HttpSession session = request.getSession();    //qq返回的信息    String code = request.getParameter("code");    String state = request.getParameter("state");    String uuid = (String) session.getAttribute("state");     if(uuid != null){        if(!uuid.equals(state)){            throw new QQStateErrorException("QQ,state錯誤");        }    }      //Step2:通過Authorization Code獲取Access Token    String backUrl = http + "/index";    String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code"+            "&client_id=" + QQHttpClient.APPID +            "&client_secret=" + QQHttpClient.APPKEY +            "&code=" + code +            "&redirect_uri=" + backUrl;     String access_token = QQHttpClient.getAccessToken(url);     //Step3: 獲取回調后的 openid 值    url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;    String openid = QQHttpClient.getOpenID(url);     //Step4:獲取QQ用戶信息    url = "https://graph.qq.com/user/get_user_info?access_token=" + access_token +            "&oauth_consumer_key="+ QQHttpClient.APPID +            "&openid=" + openid;     //返回用戶的信息    JSONObject jsonObject = QQHttpClient.getUserInfo(url);     //也可以放到redis和MySQL中,只取出了部分數據,根據自己需要取    session.setAttribute("openid",openid);  //openid,用來唯一標識qq用戶    session.setAttribute("nickname",(String)jsonObject.get("nickname")); //QQ名    session.setAttribute("figureurl_qq_2",(String)jsonObject.get("figureurl_qq_2")); //大小為100*100像素的QQ頭像URL     //響應重定向到home路徑    return "redirect:/home";}

QQ客戶端類QQHttpClient:

主要用于QQ消息返回

import com.alibaba.fastjson.JSONObject;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils; import JAVA.io.IOException; public class QQHttpClient {    //QQ互聯中提供的 appid 和 appkey    public static final String APPID = "appid";     public static final String APPKEY = "appkey";      private static JSONObject parseJSONP(String jsonp){        int startIndex = jsonp.indexOf("(");        int endIndex = jsonp.lastIndexOf(")");         String json = jsonp.substring(startIndex + 1,endIndex);         return JSONObject.parseobject(json);    }    //qq返回信息:access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14    public static String getAccessToken(String url) throws IOException {        CloseableHttpClient client = HttpClients.createDefault();        String token = null;         HttpGet httpGet = new HttpGet(url);        HttpResponse response = client.execute(httpGet);        HttpEntity entity = response.getEntity();         if(entity != null){            String result = EntityUtils.toString(entity,"UTF-8");            if(result.indexOf("access_token") >= 0){                String[] array = result.split("&");                for (String str : array){                    if(str.indexOf("access_token") >= 0){                        token = str.substring(str.indexOf("=") + 1);                        break;                    }                }            }        }         httpGet.releaseConnection();        return token;    }    //qq返回信息:callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} ); 需要用到上面自己定義的解析方法parseJSONP    public static String getOpenID(String url) throws IOException {        JSONObject jsonObject = null;        CloseableHttpClient client = HttpClients.createDefault();         HttpGet httpGet = new HttpGet(url);        HttpResponse response = client.execute(httpGet);        HttpEntity entity = response.getEntity();         if(entity != null){            String result = EntityUtils.toString(entity,"UTF-8");            jsonObject = parseJSONP(result);        }         httpGet.releaseConnection();         if(jsonObject != null){            return jsonObject.getString("openid");        }else {            return null;        }    }     //qq返回信息:{ "ret":0, "msg":"", "nickname":"YOUR_NICK_NAME", ... },為JSON格式,直接使用JSONObject對象解析    public static JSONObject getUserInfo(String url) throws IOException {        JSONObject jsonObject = null;        CloseableHttpClient client = HttpClients.createDefault();         HttpGet httpGet = new HttpGet(url);        HttpResponse response = client.execute(httpGet);        HttpEntity entity = response.getEntity();          if(entity != null){            String result = EntityUtils.toString(entity,"UTF-8");            jsonObject = JSONObject.parseObject(result);        }         httpGet.releaseConnection();         return jsonObject;    }}

異常類QQStateErrorException:

public class QQStateErrorException extends Exception {    public QQStateErrorException() {        super();    }     public QQStateErrorException(String message) {        super(message);    }     public QQStateErrorException(String message, Throwable cause) {        super(message, cause);    }     public QQStateErrorException(Throwable cause) {        super(cause);    }     protected QQStateErrorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {        super(message, cause, enableSuppression, writableStackTrace);    }}

首頁controller用于跳轉頁面

@Controllerpublic class IndexController {     @GetMapping({"/index", "/"})    public String index(){        return "index";    }     @GetMapping("/home")    public String home(HttpSession session, Model model){        String openid = (String) session.getAttribute("openid");        String nickname = (String) session.getAttribute("nickname");        String figureurl_qq_2 = (String) session.getAttribute("figureurl_qq_2");         model.addAttribute("openid",openid);        model.addAttribute("nickname",nickname);        model.addAttribute("figureurl_qq_2",figureurl_qq_2);         return "home";    }}

還有兩個簡單的登錄頁面和信息頁面

index.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body>    <a href="/qq/login">QQ登錄</a></body></html>

home.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><div>    <img th:src="${figureurl_qq_2}"></div><span th:text="${openid}"></span><span th:text="${nickname}"></span></body></html>

最后附上下載地址:https://github.com/machaoyin/qqdemo

 

關注大話編程,一起提升技能。

分享到:
標簽:第三方 登錄 Java
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定