'java實現QQ登錄'

Java 騰訊QQ GitHub JSON BigDataKer 2019-09-05
"

準備工作

1.雲服務器

2.備案的域名

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

一、申請QQ互聯,併成為開發者

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

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

"

準備工作

1.雲服務器

2.備案的域名

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

一、申請QQ互聯,併成為開發者

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

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

java實現QQ登錄

審核通過後,點擊創建應用

"

準備工作

1.雲服務器

2.備案的域名

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

一、申請QQ互聯,併成為開發者

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

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

java實現QQ登錄

審核通過後,點擊創建應用

java實現QQ登錄

"

準備工作

1.雲服務器

2.備案的域名

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

一、申請QQ互聯,併成為開發者

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

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

java實現QQ登錄

審核通過後,點擊創建應用

java實現QQ登錄

java實現QQ登錄

"

準備工作

1.雲服務器

2.備案的域名

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

一、申請QQ互聯,併成為開發者

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

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

java實現QQ登錄

審核通過後,點擊創建應用

java實現QQ登錄

java實現QQ登錄

java實現QQ登錄

審核通過後,就可以使用APP ID 和 APP Key

"

準備工作

1.雲服務器

2.備案的域名

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

一、申請QQ互聯,併成為開發者

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

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

java實現QQ登錄

審核通過後,點擊創建應用

java實現QQ登錄

java實現QQ登錄

java實現QQ登錄

審核通過後,就可以使用APP ID 和 APP Key

java實現QQ登錄

二、編寫java代碼

github:https://github.com/sansheng741/QQLogin

項目結構

"

準備工作

1.雲服務器

2.備案的域名

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

一、申請QQ互聯,併成為開發者

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

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

java實現QQ登錄

審核通過後,點擊創建應用

java實現QQ登錄

java實現QQ登錄

java實現QQ登錄

審核通過後,就可以使用APP ID 和 APP Key

java實現QQ登錄

二、編寫java代碼

github:https://github.com/sansheng741/QQLogin

項目結構

java實現QQ登錄

yml配置

server:

port: 80

qq:

oauth:

http: //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>

QQController

package com.ck.blog.controller;

import com.alibaba.fastjson.JSONObject;

import com.ck.blog.exception.StateErrorException;

import com.ck.blog.utils.QQHttpClient;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

import java.net.URLEncoder;

import java.util.UUID;

/**

* @author ck

* @create 2019-05-18 20:32

*/

@Controller

public class QQController {

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

private String http;

/**

* 發起請求

* @param session

* @return

*/

@GetMapping("/qq/oauth")

public String qq(HttpSession session){

//QQ互聯中的回調地址

String backUrl = http + "/qq/callback";

//用於第三方應用防止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) +

"&state=" + uuid;

return "redirect:" + url;

}

/**

* QQ回調

* @param request

* @return

*/

@GetMapping("/qq/callback")

public String qqcallback(HttpServletRequest request) throws Exception {

HttpSession session = request.getSession();

//qq返回的信息:http://graph.qq.com/demo/index.jsp?code=9A5F************************06AF&state=test

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 StateErrorException("QQ,state錯誤");

}

}

//Step2:通過Authorization Code獲取Access Token

String backUrl = http + "/qq/callback";

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

return "redirect:/home";

}

}

QQHttpClient

package com.ck.blog.utils;

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;

/**

* @author ck

* @create 2019-05-18 20:32

* QQ工具類(主要用於解析QQ返回的信息)

*/

public class QQHttpClient {

//QQ互聯中提供的 appid 和 appkey

public static final String APPID = "xxxxxxxx";

public static final String APPKEY = "xxxxxxxxxx";

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;

}

}

IndexController

package com.ck.blog.controller;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpSession;

/**

* @author ck

* @create 2019-05-18 20:31

*/

@Controller

public 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" xmlns:th="http://www.thymeleaf.org">

<head>

<meta charset="UTF-8">

<title>登錄頁</title>

</head>

<body>

<a href="/qq/oauth">QQ授權登錄</a>

</body>

</html>

home.html

<!DOCTYPE html>

<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>

<meta charset="UTF-8">

<title>QQ授權成功</title>

</head>

<body>

<div>

openid:[[${openid}]]

</div>

<div>

nickName:[[${nickname}]]

</div>

<div>

<img th:src="${figureurl_qq_2}">

</div>

</body>

</html>

效果圖

"

準備工作

1.雲服務器

2.備案的域名

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

一、申請QQ互聯,併成為開發者

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

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

java實現QQ登錄

審核通過後,點擊創建應用

java實現QQ登錄

java實現QQ登錄

java實現QQ登錄

審核通過後,就可以使用APP ID 和 APP Key

java實現QQ登錄

二、編寫java代碼

github:https://github.com/sansheng741/QQLogin

項目結構

java實現QQ登錄

yml配置

server:

port: 80

qq:

oauth:

http: //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>

QQController

package com.ck.blog.controller;

import com.alibaba.fastjson.JSONObject;

import com.ck.blog.exception.StateErrorException;

import com.ck.blog.utils.QQHttpClient;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

import java.net.URLEncoder;

import java.util.UUID;

/**

* @author ck

* @create 2019-05-18 20:32

*/

@Controller

public class QQController {

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

private String http;

/**

* 發起請求

* @param session

* @return

*/

@GetMapping("/qq/oauth")

public String qq(HttpSession session){

//QQ互聯中的回調地址

String backUrl = http + "/qq/callback";

//用於第三方應用防止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) +

"&state=" + uuid;

return "redirect:" + url;

}

/**

* QQ回調

* @param request

* @return

*/

@GetMapping("/qq/callback")

public String qqcallback(HttpServletRequest request) throws Exception {

HttpSession session = request.getSession();

//qq返回的信息:http://graph.qq.com/demo/index.jsp?code=9A5F************************06AF&state=test

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 StateErrorException("QQ,state錯誤");

}

}

//Step2:通過Authorization Code獲取Access Token

String backUrl = http + "/qq/callback";

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

return "redirect:/home";

}

}

QQHttpClient

package com.ck.blog.utils;

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;

/**

* @author ck

* @create 2019-05-18 20:32

* QQ工具類(主要用於解析QQ返回的信息)

*/

public class QQHttpClient {

//QQ互聯中提供的 appid 和 appkey

public static final String APPID = "xxxxxxxx";

public static final String APPKEY = "xxxxxxxxxx";

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;

}

}

IndexController

package com.ck.blog.controller;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpSession;

/**

* @author ck

* @create 2019-05-18 20:31

*/

@Controller

public 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" xmlns:th="http://www.thymeleaf.org">

<head>

<meta charset="UTF-8">

<title>登錄頁</title>

</head>

<body>

<a href="/qq/oauth">QQ授權登錄</a>

</body>

</html>

home.html

<!DOCTYPE html>

<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>

<meta charset="UTF-8">

<title>QQ授權成功</title>

</head>

<body>

<div>

openid:[[${openid}]]

</div>

<div>

nickName:[[${nickname}]]

</div>

<div>

<img th:src="${figureurl_qq_2}">

</div>

</body>

</html>

效果圖

java實現QQ登錄

————————————————

版權聲明:本文為CSDN博主「有酒醉三生丶」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處鏈接及本聲明。

原文鏈接:https://blog.csdn.net/qq_37618797/article/details/90344835

"

相關推薦

推薦中...