原创

通过QQ号获取QQ头像和昵称

温馨提示:
本文最后更新于 2018年04月24日,已超过 2,195 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

前言

本网站的评论功能,当提交评论时需要录入昵称、网址等信息,如果输入QQ号的话还可以直接获取到QQ昵称、QQ头像等信息,实现快速的填充信息。如图

获取QQ昵称

其中,获取QQ昵称是通过QQ空间的一个Api接口(JSONP格式)获取

http://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins=843977358

该接口返回如下内容

portraitCallBack({"843977358":["http://qlogo3.store.qq.com/qzone/843977358/843977358/100",26658,-1,0,0,0,"七彩狼",0]})

其中的http://qlogo3.store.qq.com/qzone/843977358/843977358/100是QQ空间头像,七彩狼就是QQ昵称

获取QQ头像

可以通过下面这两个链接中的任意一个

http://q1.qlogo.cn/g?b=qq&nk=843977358&s=40
http://q2.qlogo.cn/headimg_dl?dst_uin=843977358&spec=40

其中nk为QQ号,s为头像的尺寸

参数s 对应的尺寸 
 1 40 × 40
 2 40 × 40
 3 100 × 100
 4 140 × 140
 5 640 × 640
 40 40 × 40
 100 100 × 100

Java获取、包装数据

@PostMapping("/qq/{qq}")
public ResponseVO qq(@PathVariable("qq") String qq) {
	if (StringUtils.isEmpty(qq)) {
		return ResultUtil.error("");
	}
	Map<String, String> resultMap = new HashMap<>(4);
	String nickname = "匿名";
	String json = RestClientUtil.get("http://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins=" + qq, "GBK");
	if (!StringUtils.isEmpty(json)) {
		try {
			json = json.replaceAll("portraitCallBack|\\\\s*|\\t|\\r|\\n", "");
			json = json.substring(1, json.length() - 1);
			LOG.info(json);
			JSONObject object = JSONObject.parseObject(json);
			JSONArray array = object.getJSONArray(qq);
			nickname = array.getString(6);
		} catch (Exception e) {
			LOG.error("通过QQ号获取用户昵称发生异常", e);
		}
	}
	resultMap.put("avatar", "https://q1.qlogo.cn/g?b=qq&nk=" + qq + "&s=40");
	resultMap.put("nickname", nickname);
	resultMap.put("email", qq + "@qq.com");
	resultMap.put("url", "https://user.qzone.qq.com/" + qq);
	return ResultUtil.success(null, resultMap);
}

注:RestClientUtil类为普通的发起HTTP请求的工具类,可自己实现,也可在文末的源码链接中获取

控制台打印结果

2018-04-24 17:58:30 [com.zyd.blog.util.RestClientUtil:106] INFO  com.zyd.blog.util.RestClientUtil - RestClientUtil url: http://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins=843977358, response: 200 : OK
2018-04-24 17:59:23 [com.zyd.blog.controller.RestApiController:105] INFO  com.zyd.blog.controller.RestApiController - {"843977358":["http://qlogo3.store.qq.com/qzone/843977358/843977358/100",26658,-1,0,0,0,"七彩狼",0]}

结语

本文Java代码源于本人的开源博客>>快速链接地址<<欢迎各位关注、支持,


正文到此结束
本文目录