最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java實現(xiàn)QQ第三方登錄的示例代碼

 更新時間:2019年11月08日 11:56:40   作者:一念之間_mcy  
這篇文章主要介紹了Java實現(xiàn)QQ第三方登錄的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

前期準備工作

1.云服務器

2.備案的域名

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

如何修改hosts文件:http://www.fzitv.net/diannaojichu/319774.html

申請QQ互聯(lián),并成為開發(fā)者

申請QQ互聯(lián)創(chuàng)建應用時需要備案域名,所以建議提前準備備案域名。

QQ互聯(lián):https://connect.qq.com/index.html

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

審核通過后創(chuàng)建應用

應用創(chuàng)建通過審核后,就可以使用APP ID 和 APP Key

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

項目結(jié)構(gòu):

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

server.port=80
server.servlet.context-path=/
 
#qq互聯(lián)
qq.oauth.http:QQ互聯(lián)中申請?zhí)顚懙木W(wǎng)站地址

在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>

發(fā)送QQ登錄請求

定義全局變量獲取配置文件中的網(wǎng)站地址

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

定義登錄回調(diào)地址(可以用網(wǎng)站地址拼接或者直接寫)

//QQ互聯(lián)中的回調(diào)地址
String backUrl = http + "/index";

登錄請求方法代碼

@GetMapping("/qq/login")
public String qq(HttpSession session) throws UnsupportedEncodingException {
  //QQ互聯(lián)中的回調(diào)地址
  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;
}

回調(diào)返回參數(shù)信息說明:

參數(shù)名稱 描述
ret 返回碼。詳見公共返回碼說明#OpenAPI V3.0 返回碼
msg 如果錯誤,返回錯誤信息。
is_lost 判斷是否有數(shù)據(jù)丟失。如果應用不使用cache,不需要關心此參數(shù)。

0或者不返回:沒有數(shù)據(jù)丟失,可以緩存。
1:有部分數(shù)據(jù)丟失或錯誤,不要緩存。

nickname 昵稱。
gender 性別。
country 國家(當pf=qzone、pengyou或qplus時返回)。
province ?。ó攑f=qzone、pengyou或qplus時返回)。
city 市(當pf=qzone、pengyou或qplus時返回)。
figureurl 頭像URL。詳見:前端頁面規(guī)范#6. 關于用戶頭像的獲取和尺寸說明。
openid 用戶QQ號碼轉(zhuǎn)化得到的ID(當pf=qplus時返回)。
qq_level 用戶QQ等級(當pf=qplus時返回)。
qq_vip_level 用戶QQ會員等級(當pf=qplus時返回)。
qplus_level 用戶Q+等級(當pf=qplus時返回)。
is_yellow_vip 是否為黃鉆用戶(0:不是; 1:是)。

(當pf=qzone、pengyou或qplus時返回)

is_yellow_year_vip 是否為年費黃鉆用戶(0:不是; 1:是)。

(當pf=qzone、pengyou或qplus時返回)

yellow_vip_level 黃鉆等級,目前最高級別為黃鉆8級(如果是黃鉆用戶才返回此參數(shù))。

(當pf=qzone、pengyou或qplus時返回)

is_yellow_high_vip 是否為豪華版黃鉆用戶(0:不是; 1:是)。

(當pf=qzone、pengyou或qplus時返回)

is_blue_vip 是否為藍鉆用戶(0:不是; 1:是)。

(當pf=qqgame或3366時返回)

is_blue_year_vip 是否為年費藍鉆用戶(0:不是; 1:是)。

(當pf=qqgame或3366時返回)

blue_vip_level 藍鉆等級(如果是藍鉆用戶才返回此參數(shù))。

(當pf=qqgame或3366時返回)

3366_level 3366用戶的大等級。

(當pf=3366時返回)

3366_level_name 3366用戶的等級名,如小游游、小游仙。

(當pf=3366時返回)

3366_grow_level 3366用戶的成長等級。

(當pf=3366時返回)

3366_grow_value 3366用戶的成長值。

(當pf=3366時返回)

is_super_blue_vip 是否是豪華藍鉆。

(當pf=qqgame或3366時返回)

正確返回示例:

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

請求成功,用戶確認登錄后回調(diào)方法

@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: 獲取回調(diào)后的 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中,只取出了部分數(shù)據(jù),根據(jù)自己需要取
  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互聯(lián)中提供的 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用于跳轉(zhuǎn)頁面

@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">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <a href="/qq/login" rel="external nofollow" >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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • SpringBoot多環(huán)境打包與配置文件排除實踐記錄

    SpringBoot多環(huán)境打包與配置文件排除實踐記錄

    本文介紹了SpringBoot項目多環(huán)境打包與配置文件排除實踐,包括多環(huán)境配置的實現(xiàn)方法、打包時排除配置文件的方法以及動態(tài)加載外部配置文件的最佳實踐,感興趣的朋友跟隨小編一起看看吧
    2024-11-11
  • Spring MVC 404 Not Found無錯誤日志的解決方法

    Spring MVC 404 Not Found無錯誤日志的解決方法

    這篇文章主要為大家詳細介紹了Spring MVC 404 Not Found無錯誤日志的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • Java中的ThreadPoolExecutor線程池原理細節(jié)解析

    Java中的ThreadPoolExecutor線程池原理細節(jié)解析

    這篇文章主要介紹了Java中的ThreadPoolExecutor線程池原理細節(jié)解析,ThreadPoolExecutor是一個線程池,最多可使用7個參數(shù)來控制線程池的生成,使用線程池可以避免創(chuàng)建和銷毀線程的資源損耗,提高響應速度,并且可以管理線程池中線程的數(shù)量和狀態(tài)等等,需要的朋友可以參考下
    2023-12-12
  • Spring boot基于ScheduledFuture實現(xiàn)定時任務

    Spring boot基于ScheduledFuture實現(xiàn)定時任務

    這篇文章主要介紹了Spring boot基于ScheduledFuture實現(xiàn)定時任務,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-06-06
  • 在CentOS7(有圖形化界面)上安裝maven和idea的詳細教程

    在CentOS7(有圖形化界面)上安裝maven和idea的詳細教程

    這篇文章主要介紹了在CentOS7(有圖形化界面)上安裝maven和idea的詳細教程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03
  • 基于Java實現(xiàn)計數(shù)排序,桶排序和基數(shù)排序

    基于Java實現(xiàn)計數(shù)排序,桶排序和基數(shù)排序

    這篇文章主要為大家詳細介紹了計數(shù)排序,桶排序和基數(shù)排序的多種語言的實現(xiàn)(JavaScript、Python、Go語言、Java),感興趣的小伙伴可以了解一下
    2022-12-12
  • java long轉(zhuǎn)String +Codeforces110A案例

    java long轉(zhuǎn)String +Codeforces110A案例

    這篇文章主要介紹了java long轉(zhuǎn)String +Codeforces110A案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • Java枚舉類enum介紹

    Java枚舉類enum介紹

    這篇文章主要介紹了Java枚舉類enum介紹,和其它普通類一樣,enum同樣可以有成員變量、方法、構(gòu)造器,也可以實現(xiàn)一個或多個接口,需要的朋友可以參考下
    2015-04-04
  • Java語言實現(xiàn)簡單FTP軟件 FTP本地文件管理模塊實現(xiàn)(9)

    Java語言實現(xiàn)簡單FTP軟件 FTP本地文件管理模塊實現(xiàn)(9)

    這篇文章主要為大家詳細介紹了Java語言實現(xiàn)簡單FTP軟件,F(xiàn)TP本地文件管理模塊的實現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • java識別一篇文章中某單詞出現(xiàn)個數(shù)的方法

    java識別一篇文章中某單詞出現(xiàn)個數(shù)的方法

    這篇文章主要介紹了java識別一篇文章中某單詞出現(xiàn)個數(shù)的方法,涉及java字符解析操作的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-10-10

最新評論

连州市| 信丰县| 新民市| 黑河市| 三门县| 怀宁县| 夏邑县| 文成县| 柘荣县| 政和县| 通州市| 宜都市| 蒙阴县| 巩义市| 襄汾县| 荥经县| 沭阳县| 工布江达县| 藁城市| 晴隆县| 濮阳县| 佛教| 北碚区| 耿马| 九寨沟县| 永新县| 谢通门县| 武夷山市| 台东县| 虞城县| 哈密市| 虎林市| 富民县| 大石桥市| 广汉市| 卓资县| 随州市| 白朗县| 阿荣旗| 漳浦县| 万宁市|