02 调用获取用户信息的api

  • Post author:
  • Post category:其他


在完成百度开发者注册及配置的基础上,我们就可以调用api获取用户信息。

1、介绍授权流程

Server端使用百度OAuth2.0授权调用开放API流程有三步:

    1. 引导用户到如下地址进行授权:
http://openapi.baidu.com/oauth/2.0/authorize?
    response_type=code&
    client_id=YOUR_CLIENT_ID&
    redirect_uri=YOUR_REGISTERED_REDIRECT_URI&
    scope=email&
    display=popup
    1. 如果用户同意授权,页面跳转至 YOUR_REGISTERED_REDIRECT_URI/?code=CODE 。
    1. 换取Access Token。
https://openapi.baidu.com/oauth/2.0/token?
    grant_type=authorization_code&
    code=CODE&
    client_id=YOUR_CLIENT_ID&
    client_secret=YOUR_CLIENT_SECRET&
    redirect_uri=YOUR_REGISTERED_REDIRECT_URI

返回值

{
    "access_token": "1.a6b7dbd428f731035f771b8d15063f61.86400.1292922000-2346678-124328",
    "expires_in": 86400,
    "refresh_token": "2.385d55f8615fdfd9edb7c4b5ebdc3e39.604800.1293440400-2346678-124328",
    "scope": "basic email",
    "session_key": "ANXxSNjwQDugf8615OnqeikRMu2bKaXCdlLxn",
    "session_secret": "248APxvxjCZ0VEC43EYrvxqaK4oZExMB",
}
    1. 使用获得的OAuth2.0 Access Token调用API

2、操作步骤:

  • 1 创建一个基于maven的web工程,笔者这里使用servlet,读者亦可以采用其他方式如springmvc、springboot等。

    在pom.xml中加入以下依赖:
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20170516</version>
        </dependency>
  • 2 创建登录页面index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>oauth2</title>
<style>
    body{ text-align:center} 
    #divcss5{margin:0 auto;border:1px solid #000;width:300px;height:120px} 
</style>
<script>
    function clickme() {
        window.location.href = "oauth";
    };
</script>


</head>
<body>
    <div id="divcss5">
        账号:<input type="text" /><br /> 
        密码:<input type="password" /><br /> 
        <input type="submit" value="登录" /><br /><br /> 
        <input id="abutton" type="button" value="百度账号登录"    onclick="clickme()" />
    </div>
</body>
</html>
  • 3 创建登录成功页面third_login_success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>oauth2</title>
<style>
    body{ text-align:center} 
    #divcss5{margin:0 auto;border:0px solid #000;width:300px;height:120px} 
</style>
</head>
<body>
    <div id="divcss5">
        <h1>您好!${username}<% String username=(String)request.getAttribute("username"); %></h1>
    </div>
</body>
</html>
  • 4 创建常量类
package constant;

public interface BaiduCconstant {
    
    //API Key,这是笔者的api key,已经做微调,请读者使用自己的apikey
    String CLIENT_ID = "jYy1NG8S9enC3dYfIkYk4Zdsh";
    
    //授权回调页,注意要使用urlencode加密
    String REDIRECT_URI = "http%3A%2F%2Fzhangli123.com%3A8080%2Fthird_login";
    
    //Secret Key,这是笔者的秘钥,已经做微调,请读者使用自己的秘钥
    String SECRET_KEY = "VGirK93LRlHUQv2FCQbzE5ZgaAMk9YsEl";

    /**
     * 获取当前登录用户的信息
     * 我们这里只用了一个获取用户信息的api,其他api介绍列表信息在以下地址
     * http://developer.baidu.com/wiki/index.php?title=docs/oauth/rest/file_data_apis_list
     */
    String PASSPORT_USERS_GETLOGGEDINUSER = "passport/users/getLoggedInUser";

}

  • 5 创建完成api回调的接口
package controller;

import constant.BaiduCconstant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/oauth")
public class OauthController extends HttpServlet {

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = "http://openapi.baidu.com/oauth/2.0/authorize?response_type=code"
                + "&client_id="+BaiduCconstant.CLIENT_ID
                + "&redirect_uri="+BaiduCconstant.REDIRECT_URI;
        response.sendRedirect(url);
        
    }

}
  • 6 创建通过code换取token,在调用相关API的接口
package controller;

import constant.BaiduCconstant;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
@WebServlet("/third_login")
public class ThirdLoginController extends HttpServlet {

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code = request.getParameter("code");
        if (code != null) {
            String url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code"
                    + "&code=" + code
                    + "&client_id=" + BaiduCconstant.CLIENT_ID
                    + "&client_secret=" + BaiduCconstant.SECRET_KEY
                    + "&redirect_uri=" + BaiduCconstant.REDIRECT_URI;
            //根据返回原code获取包含access_token的json字符串
            String resultJsonStr = httpGet(url);
            //将得到的结果转成json对象
            JSONObject json = new JSONObject(resultJsonStr);
            //获取access_token(访问令牌)
            String accessToken = (String) json.get("access_token");
            if (accessToken != null) {
                //根据access_token获取用户的令牌
                String u = "https://openapi.baidu.com/rest/2.0/"
                        + BaiduCconstant.PASSPORT_USERS_GETLOGGEDINUSER
                        + "?access_token=" + accessToken;
                String result = httpGet(u);
                JSONObject jo = new JSONObject(result);
                String uname = (String) jo.get("uname");
                System.out.println("用户名:" + uname);

                //使用返回的第三方用户信息完成本服务用户的注册【从来没有用第三方登陆过】
                String userid = (String) jo.get("uid") + (String) jo.get("openid");//把这个信息存储到tbuser表中新增的一条记录中【user表中应该多出几列用来存储第三方信息】
                //存储userid到数据库中
                if ("userid".equals("userid"))//在数据库中通过userid查询出来不为空,则证明之前已经使用百度第三方登陆过,则不必再次插入一条新纪录
                {
                    //进到下一步,登录成功
                } else {
                    //存储到数据库
                }
                //以上的这些操作就是为了借助这些国民应用,减少用户进入我们系统所消耗的注册和登陆时间
                request.setAttribute("username", uname);
                request.getRequestDispatcher("third_login_success.jsp").forward(request, response);
            } else {
                //如果为空,做错误处理
            }
        } else {
            //如果为空,做错误处理
        }
    }

    /**
     * 发送http get类型请求,获取返回结果
     */
    private String httpGet(String url) throws MalformedURLException, IOException, UnsupportedEncodingException {
        URL ur = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) ur.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        byte[] buff = new byte[is.available()];
        is.read(buff);
        String ret = new String(buff, "utf-8");
        is.close();
        conn.disconnect();
        return ret;
    }
}
  • 7 启动项目,点击百度账号登录,就会看到我们需要登录百度账号,并获取到了百度账号下的用户名称。



版权声明:本文为langli204910原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。