用Java实现QQ登录

编程知识 更新时间:2023-05-01 22:44:06

Java实现QQ登录

写了一个个人网站,增加一个登录的地方,自己写登录太麻烦,而且用户一般也不愿意去登录,接入QQ互联,实现QQ一键登录。所有前提是你得有一个IP地址和域名。
==ps:==用处不大,主要是写着玩

1 进入qq互联官网进入点击头像个创建提交申请

2 选择个人接入,按照步骤填写注册资料
创建成功通过后会哦显示接入的个人信息。

3 审核成功后点击下面的开始创建,按步骤完成创建过程。

4 创建成功后可以查看APP IDAPP key,很重要

在应用管理界面可以查看如上信息,点击查看就可以看到如下关键信息。

往下划在平台信息里可以看到网站地址和网站回调域,回调域一般是`@requestMapping()``中写的请求地址

5 登录页面

<a href"/login">qq登录</a>

6 配置qqconnectconfig.properties,与application.properties同一级

app_ID = 你的App ID
app_KEY = 你的App key
redirect_URI = 你的回调域
scope = get_user_info,add_topic,add_one_blog,add_album,upload_pic,list_album,add_share,check_page_fans,add_t,add_pic_t,del_t,get_repost_list,get_info,get_other_info,get_fanslist,get_idollist,add_idol,del_ido,get_tenpay_addr
baseURL = https://graph.qq/
getUserInfoURL = https://graph.qq/user/get_user_info
accessTokenURL = https://graph.qq/oauth2.0/token
authorizeURL = https://graph.qq/oauth2.0/authorize
getOpenIDURL = https://graph.qq/oauth2.0/me
addTopicURL = https://graph.qq/shuoshuo/add_topic
addBlogURL = https://graph.qq/blog/add_one_blog
addAlbumURL = https://graph.qq/photo/add_album
uploadPicURL = https://graph.qq/photo/upload_pic
listAlbumURL = https://graph.qq/photo/list_album
addShareURL = https://graph.qq/share/add_share
checkPageFansURL = https://graph.qq/user/check_page_fans
addTURL = https://graph.qq/t/add_t
addPicTURL = https://graph.qq/t/add_pic_t
delTURL = https://graph.qq/t/del_t
getWeiboUserInfoURL = https://graph.qq/user/get_info
getWeiboOtherUserInfoURL = https://graph.qq/user/get_other_info
getFansListURL = https://graph.qq/relation/get_fanslist
getIdolsListURL = https://graph.qq/relation/get_idollist
addIdolURL = https://graph.qq/relation/add_idol
delIdolURL = https://graph.qq/relation/del_idol
getTenpayAddrURL = https://graph.qq/cft_info/get_tenpay_addr
getRepostListURL = https://graph.qq/t/get_repost_list
version = 2.0.0.0

7导入依赖

<!--热部署工具-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <!--QQ登录-->
        <!-- https://mvnrepository/artifact/net.gplatform/Sdk4J -->
        <dependency>
            <groupId>net.gplatform</groupId>
            <artifactId>Sdk4J</artifactId>
            <version>2.0</version>
        </dependency>

8 编写controller

	 //获取用户当前页面的url,方便返回登录之前的页面,
	private static String returnUrl = ""	
	/**
     * @Description: qq登录的入口
     */
    @GetMapping("/login")
    public ResponseEntity<Void> loginByQQ(HttpServletRequest request, HttpServletResponse response){
       
        returnUrl = request.getParameter("returnUrl");
        response.setContentType("text/html,charset=utf-8");
        try {
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
            return ResponseEntity.ok().build();
        } catch (IOException | QQConnectException e) {
            LOGGER.warn("请求QQ登录失败, {}",e.getMessage());
        }
        return ResponseEntity.badRequest().build();
    }
    /**
     *
     * 此处的qqlogin必须与你的网站回调域一致
     * @Description: 登录获取数据
     */
    @RequestMapping("/qqlogin")
    public String login(HttpServletRequest request,HttpServletResponse response){
        User user = new User();
        try {
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
            //用来或用户信息,get_user_info参数
          	String accessToken   = null;
            String openID = null;
            long tokenExpireIn = 0L;
            if (accessTokenObj.getAccessToken().equals("")) {
                LOGGER.error("没有获取到响应参数");
            }else {
                accessToken = accessTokenObj.getAccessToken();
                tokenExpireIn = accessTokenObj.getExpireIn();
                System.out.println(String.valueOf(tokenExpireIn));
                // 利用获取到的accessToken 去获取当前用的openid -------- start
                OpenID openIDObj =  new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();

                UserInfo userInfo = new UserInfo(accessToken, openID);
                UserInfoBean userInfoBean = userInfo.getUserInfo();
                /*
				* 此处获取用户信息后可以在service层重新保存用户部分信息用作登录展示
				* 比如写一个UserInfo类用于信息展示,将UserInfo对应的用户信息通过加密的方式保存到
				* Cookie中,每次请求都会携带Cookie,然后解密重新设置过期时间再进行加密保存。
				* 用户退出就可以将Cookie信息删除,这样就不需要依赖QQ登录本身保存的信息了。
				*/
                if (userInfoBean.getRet()==0){
                    //获取qq空间头像,暂不知怎么获取qq头像
                    user.setAvatar(userInfoBean.getAvatar().getAvatarURL50());
                    //用户openId,唯一标识
                    user.setOpenId(openID);
                    //用户qq昵称
                    user.setNickName(userInfoBean.getNickname());
                    //用户性别
                    user.setGender(userInfoBean.getGender());
                }else {
                    LOGGER.warn("很抱歉,我们没能正确获取到您的信息,原因是:{} ", userInfoBean.getMsg());
                }
            }
        } catch (QQConnectException e) {
            LOGGER.error("qq连接发生异常 {}",e.getMessage());
        }
        return "redirect:"+returnUrl;
    }

获取用户信息API

get_user_info

通过上面的方法可以获取的用户信息较少,并且获取的头像是QQ空间的头像而不是QQ头像,如果没有QQ空间的话,那么就没有用户头像了。可以通过get_user_info获取用户更多的信息,比如QQ头像!

新建一个用户信息实体类

根据返回的json创建用户对象

package com.cx.pojo;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Transient;

/**
 *@JsonIgnoreProperties(ignoreUnknown = true) 忽略部分不能匹配的字段
 *@JsonProperty(value = "***"),因为获取的用户信息json不符合java命名规范,所有需要添加字段映射
 * @author 苍晓
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResultInfo {
    private int ret;
    private String msg;
    @JsonProperty(value = "is_lost")
    private boolean isLost;
    private String nickname;
    private String gender;
    @JsonProperty(value = "gender_type")
    private String genderType;
    private String province;
    private String city;
    private String year;
    private String constellation;
    private String figureurl;
    @JsonProperty(value = "figureurl_1")
    private String figureUrl1;
    @JsonProperty(value = "figureurl_2")
    private String figureUrl12;
    @JsonProperty(value = "figureurl_qq_1")
    private String figureUrlQq1;
    @JsonProperty(value = "figureurl_qq_2")
    private String figureUrlQq2;
    @JsonProperty(value = "figureurl_qq")
    private String figureUrlQq;
    @JsonProperty(value = "figureurl_type")
    private String figureUrlType;
    @JsonProperty(value = "is_yellow_vip")
    private String isYellowVip;
    private int vip;
    @JsonProperty(value = "yellow_vip_level")
    private int yellowVipLevel;
    private int level;
    @JsonProperty(value = "is_yellow_year_vip")
    private String isYellowYearVip;

}

RestTemplate配置

package com.blog.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * @author 苍晓
 */
@Configuration
public class RestTemplateConfig {
    
    @Bean
    public RestTemplate getRestTemplate(){

        RestTemplate restTemplate = new RestTemplate();
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
      /*
      *经过尝试,此处需要加一个MediaType.TEXT_HTML的返回类型,否则一直报错,解析不了返回信息。
      */
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON,
                MediaType.TEXT_HTML));
        restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
        return restTemplate;
    }
}

测试获取用户信息

	//注入rest请求模板
	@Autowired
    private RestTemplate restTemplate;

    private final String preUrl="https://graph.qq/user/get_user_info?" +
            "access_token=获取的登录用户AccessToken" +
            "&oauth_consumer_key=你的AppID" +
            "&openid=获取的登录用户的openID";
	@Test
    void qqInfo() {
        String object = this.restTemplate.getForObject(preUrl, String.class);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            System.out.println("============================");
            ResultInfo resultInfo = objectMapper.readValue(object,ResultInfo.class);
            System.out.println(resultInfo);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

更多推荐

用Java实现QQ登录

本文发布于:2023-04-24 08:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/bec03d676cdf9d2eee784e57b48d8fcf.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java   QQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 100091文章数
  • 26007阅读数
  • 0评论数