账号准备
1.微博开放者平台注册
微博放者平台
登录,然后进入我的应用!
2.完善信息
微博开放者平台还是挺好认证的,大概10分钟就能搞定!
3.填写应用回调信息
客户端代码实现
1.先微博认证服务器发送请求
client_id:这个就是基本信息中的App Key
redirect_uri:这个是高级信息中的授权回调页面
服务端实现
1.编写认证成功微博的回调接口.
@GetMapping("/weibo/success")
public String weiboSuccess(@RequestParam("code") String code, HttpSession session) throws Exception {
Map<String, String> map = new HashMap<>();
map.put("client_id", "你的App Key");
map.put("client_secret", "你的App Secret");
map.put("grant_type", "authorization_code");
map.put("redirect_uri", "回调地址");
map.put("code", code);
HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());
if (response.getStatusLine().getStatusCode() == 200) {
//授权成功!!!
String json = EntityUtils.toString(response.getEntity());
System.out.println(json);//{"access_token":"xxx","remind_in":"xxx","expires_in":xxx,"uid":"xxx","isRealName":"xxx"}
// 获取用户的登录平台,然后判断用户是否该注册到系统中
return "登录成功的界面";
} else {
return "登录失败的界面";
}
}
2.获取微博开放的用户信息
可以再回调中的授权成功里面通过access_token得到微博开放的用户信息
try {
Map<String, String> query = new HashMap<>();
query.put("access_token", socialUser.getAccess_token());
query.put("uid", socialUser.getUid());
HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), query);
if (response.getStatusLine().getStatusCode() == 200) {
String json = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = JSON.parseObject(json);
String name = jsonObject.getString("name");
String gender = jsonObject.getString("gender");
// ......
register.setNickname(name);
register.setGender("m".equals(gender) ? 1 : 0);
// .....
}
} catch (Exception e) {}
核心代码就搞定了,像这种接第三方的功能,开发过程中其实屡见不鲜,后续我也会发布一些常用的三方服务整合文章!