Java中怎么實(shí)現(xiàn)QQ第三方登錄-創(chuàng)新互聯(lián)

Java中怎么實(shí)現(xiàn)QQ第三方登錄,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。

在阜陽(yáng)等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站 網(wǎng)站設(shè)計(jì)制作按需設(shè)計(jì)網(wǎng)站,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站建設(shè),成都全網(wǎng)營(yíng)銷推廣,外貿(mào)營(yíng)銷網(wǎng)站建設(shè),阜陽(yáng)網(wǎng)站建設(shè)費(fèi)用合理。

申請(qǐng)QQ互聯(lián),并成為開(kāi)發(fā)者

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

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

登錄后,點(diǎn)擊頭像,進(jìn)入認(rèn)證頁(yè)面,填寫信息,等待審核。

審核通過(guò)后創(chuàng)建應(yīng)用

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

前期工作就這些了,后面可以開(kāi)始寫代碼了。

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

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

server.port=80server.servlet.context-path=/ #qq互聯(lián)qq.oauth.http:QQ互聯(lián)中申請(qǐng)?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登錄請(qǐng)求

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

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

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

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

登錄請(qǐng)求方法代碼

@GetMapping("/qq/login")public String qq(HttpSession session) throws UnsupportedEncodingException {  //QQ互聯(lián)中的回調(diào)地址  String backUrl = http + "/index";   //用于第三方應(yīng)用防止CSRF攻擊  String uuid = UUID.randomUUID().toString().replaceAll("-","");  session.setAttribute("state",uuid);   //Step1:獲取Authorization Code  String url = "/tupian/20230522/authorize      "&client_id=" + QQHttpClient.APPID +      "&redirect_uri=" + URLEncoder.encode(backUrl, "utf-8") +      "&state=" + uuid;   return "redirect:" + url;}

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

ret      返回碼。詳見(jiàn)公共返回碼說(shuō)明#OpenAPI V3.0 返回碼。              msg      如果錯(cuò)誤,返回錯(cuò)誤信息。              is_lost      判斷是否有數(shù)據(jù)丟失。如果應(yīng)用不使用cache,不需要關(guān)心此參數(shù)。

0或者不返回:沒(méi)有數(shù)據(jù)丟失,可以緩存。      1:有部分?jǐn)?shù)據(jù)丟失或錯(cuò)誤,不要緩存。

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

(當(dāng)pf=qzone、pengyou或qplus時(shí)返回)

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

(當(dāng)pf=qzone、pengyou或qplus時(shí)返回)

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

(當(dāng)pf=qzone、pengyou或qplus時(shí)返回)

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

(當(dāng)pf=qzone、pengyou或qplus時(shí)返回)

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

(當(dāng)pf=qqgame或3366時(shí)返回)

is_blue_year_vip      是否為年費(fèi)藍(lán)鉆用戶(0:不是; 1:是)。

(當(dāng)pf=qqgame或3366時(shí)返回)

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

(當(dāng)pf=qqgame或3366時(shí)返回)

3366_level      3366用戶的大等級(jí)。

(當(dāng)pf=3366時(shí)返回)

3366_level_name      3366用戶的等級(jí)名,如小游游、小游仙。

(當(dāng)pf=3366時(shí)返回)

3366_grow_level      3366用戶的成長(zhǎng)等級(jí)。

(當(dāng)pf=3366時(shí)返回)

3366_grow_value      3366用戶的成長(zhǎng)值。

(當(dāng)pf=3366時(shí)返回)

is_super_blue_vip      是否是豪華藍(lán)鉆。

(當(dāng)pf=qqgame或3366時(shí)返回)

正確返回示例:

JSON示例:

Content-type: text/html; charset=utf-8{"ret":0,"is_lost":0,"nickname":"Peter","gender":"男","country":"中國(guó)","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}

錯(cuò)誤返回示例

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

用戶資料的接口文檔:/tupian/20230522/wikinew.open.qq.com 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錯(cuò)誤");    }  }    //Step2:通過(guò)Authorization Code獲取Access Token  String backUrl = http + "/index";  String url = "/tupian/20230522/token      "&client_id=" + QQHttpClient.APPID +      "&client_secret=" + QQHttpClient.APPKEY +      "&code=" + code +      "&redirect_uri=" + backUrl;   String access_token = QQHttpClient.getAccessToken(url);   //Step3: 獲取回調(diào)后的 openid 值  url = "/tupian/20230522/me + access_token;  String openid = QQHttpClient.getOpenID(url);   //Step4:獲取QQ用戶信息  url = "/tupian/20230522/get_user_info + access_token +      "&oauth_consumer_key="+ QQHttpClient.APPID +      "&openid=" + openid;   //返回用戶的信息  JSONObject jsonObject = QQHttpClient.getUserInfo(url);   //也可以放到Redis和mysql中,只取出了部分?jǐn)?shù)據(jù),根據(jù)自己需要取  session.setAttribute("openid",openid); //openid,用來(lái)標(biāo)識(shí)qq用戶  session.setAttribute("nickname",(String)jsonObject.get("nickname")); //QQ名  session.setAttribute("figureurl_qq_2",(String)jsonObject.get("figureurl_qq_2")); //大小為100*100像素的QQ頭像URL   //響應(yīng)重定向到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對(duì)象解析  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);  }}

首頁(yè)controller用于跳轉(zhuǎn)頁(yè)面

@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";  }}

還有兩個(gè)簡(jiǎn)單的登錄頁(yè)面和信息頁(yè)面

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><p>  <img th:src="${figureurl_qq_2}"></p><span th:text="${openid}"></span><span th:text="${nickname}"></span></body></html>


看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司,的支持。

文章名稱:Java中怎么實(shí)現(xiàn)QQ第三方登錄-創(chuàng)新互聯(lián)
文章地址:http://www.muchs.cn/article0/dhcjoo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、全網(wǎng)營(yíng)銷推廣網(wǎng)站改版、外貿(mào)建站網(wǎng)站排名、品牌網(wǎng)站設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)