百度第三方登陆

创建百度工程

1、搜索“百度开发着中心”,如图:

2、点击进入官网,如图:

3、登陆成功后,将鼠标放在用户名上,点击申请记录,如图:

4、点击百度云官网,如果是第一次登陆百度云,登陆成功后跳转到下面的界面,完善相关信息,如图:

5、激活成功后,回到下面的界面,如图:

6、点击应用管理,如图:

7、创建工程,成功后进入下面界面,如图:

注意:基本信息的中API Key Secret Key将会在编程中用到

 

8、点击安全设置,完善相关信息,如图:

 

编程:

第一步:用户访问界面

1、在Eclipse新建web项目,在WebContent文件夹下新建JSP文件,如下图:

2、在index.jsp文件中写下面代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
        function bdlogin(){
            location.href="https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=8zpRkYaTqeY7U5PtBcQabTsV&redirect_uri=http://www.willyqi.top/venu/BaiDuServlet&display=popup";
        }
</script>
<body>
<input type="button" value="百度登录" onclick="bdlogin()">
</body>
</html>

注意:client_id是上文所提到API Key    ,redirect_uri是回调地址

这次点击是我们和百度交互然后百度又返回给我们了一个code值

 

第二步:获取access_token

在项目中的Java Resources创建servlet,代码如下,完成后,导入httpclient  jar包 和fastjson jar包:

public class BaiDuServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String code = request.getParameter("code");
	    String redirect_uri= "http://www.willyqi.top/venu/BaiDuServlet";  //回调地址
        String client_secret = "0sDDGed56GKqKKEI8Bw58o48d6EBECsM";        //Secret Key
        String client_id = "8zpRkYaTqeY7U5PtBcQabTsV";                    //API Key
        String url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code="+code+"&client_id="+client_id+"&client_secret="+client_secret+"&redirect_uri="+redirect_uri+"";
        
        String content= "";
        
        try {
            //创建一个HttpClient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //创建一个Get请求
            HttpGet getReq = new HttpGet(url);
            
            getReq.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8    ");
            getReq.addHeader("Accept-Encoding", "gzip, deflate, sdch, br");
            getReq.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
            getReq.addHeader("Cache-Control","max-age=0");
            getReq.addHeader("Connection", "keep-alive");
            getReq.addHeader("Host", "openapi.baidu.com");
            getReq.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36");
             
            HttpResponse res = httpClient.execute(getReq);
            
            HttpEntity entity = res.getEntity();  
            content= EntityUtils.toString(entity,"UTF-8");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        Map<String, Object> map = JSON.parseObject(content,new TypeReference<Map<String,Object>>(){});
        String access_token = (String) map.get("access_token");
	}
}

上面用httpclient 将code传递给百度,百度会返回一组Json数据,其中包含access_token。这个access_token,具体作用就是获取到用户信息。

 

第三步:获取用户信息

public void getUserInfo(String access_token,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String content ="";
		String url = "https://openapi.baidu.com/rest/2.0/passport/users/getInfo?access_token=" + access_token + "";
		try {
			// 创建一个HttpClient对象
			CloseableHttpClient httpClient = HttpClients.createDefault();
			// 创建一个Get请求
			HttpGet getReq = new HttpGet(url);

			getReq.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8    ");
			getReq.addHeader("Accept-Encoding", "gzip, deflate, sdch, br");
			getReq.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
			getReq.addHeader("Cache-Control", "max-age=0");
			getReq.addHeader("Connection", "keep-alive");
			getReq.addHeader("Host", "openapi.baidu.com");
			getReq.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36");

			HttpEntity entity = httpClient.execute(getReq).getEntity();
			content = EntityUtils.toString(entity, "UTF-8");
			System.out.println(content);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Map<String, Object> map = JSON.parseObject(content, new TypeReference<Map<String, Object>>() {});
		System.out.println(map);

		String baiduid = (String) map.get("userid");
		System.out.println(baiduid);
		//List list = JdbcUtils.getList(User.class, "select * from user where baiduid=" + baiduid);
//		if (list.size() == 0) {
		request.setAttribute("message", map);
		request.getRequestDispatcher("/result.jsp").forward(request, response);
//		} else {
//			User user = (User) list.get(0);
//			req.getSession().setAttribute("UserInfo", user);
//			req.getRequestDispatcher("/success.jsp").forward(req, res);
//		}
	}

 

最终代码:

public class BaiDuServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取access_token
		String code = request.getParameter("code");
	    String redirect_uri= "http://www.willyqi.top/venu/BaiDuServlet";
        String client_secret = "0sDDGed56GKqKKEI8Bw58o48d6EBECsM";
        String client_id = "8zpRkYaTqeY7U5PtBcQabTsV";
        String url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code="+code+"&client_id="+client_id+"&client_secret="+client_secret+"&redirect_uri="+redirect_uri+"";
        
        String content= "";
        
        try {
            //创建一个HttpClient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //创建一个Get请求
            HttpGet getReq = new HttpGet(url);
            
            getReq.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8    ");
            getReq.addHeader("Accept-Encoding", "gzip, deflate, sdch, br");
            getReq.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
            getReq.addHeader("Cache-Control","max-age=0");
            getReq.addHeader("Connection", "keep-alive");
            getReq.addHeader("Host", "openapi.baidu.com");
            getReq.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36");
             
            HttpResponse res = httpClient.execute(getReq);
            
            HttpEntity entity = res.getEntity();  
            content= EntityUtils.toString(entity,"UTF-8");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        Map<String, Object> map = JSON.parseObject(content,new TypeReference<Map<String,Object>>(){});
        String access_token = (String) map.get("access_token");
        getUserInfo(access_token, request,  response);
	}
	//获取用户信息
	public void getUserInfo(String access_token,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String content ="";
		String url = "https://openapi.baidu.com/rest/2.0/passport/users/getInfo?access_token=" + access_token + "";
		try {
			// 创建一个HttpClient对象
			CloseableHttpClient httpClient = HttpClients.createDefault();
			// 创建一个Get请求
			HttpGet getReq = new HttpGet(url);

			getReq.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8    ");
			getReq.addHeader("Accept-Encoding", "gzip, deflate, sdch, br");
			getReq.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
			getReq.addHeader("Cache-Control", "max-age=0");
			getReq.addHeader("Connection", "keep-alive");
			getReq.addHeader("Host", "openapi.baidu.com");
			getReq.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36");

			HttpEntity entity = httpClient.execute(getReq).getEntity();
			content = EntityUtils.toString(entity, "UTF-8");
			System.out.println(content);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Map<String, Object> map = JSON.parseObject(content, new TypeReference<Map<String, Object>>() {});
		System.out.println(map);

		String baiduid = (String) map.get("userid");
		System.out.println(baiduid);
		//List list = JdbcUtils.getList(User.class, "select * from user where baiduid=" + baiduid);
//		if (list.size() == 0) {
		request.setAttribute("message", map);
		request.getRequestDispatcher("/result.jsp").forward(request, response);
//		} else {
//			User user = (User) list.get(0);
//			req.getSession().setAttribute("UserInfo", user);
//			req.getRequestDispatcher("/success.jsp").forward(req, res);
//		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值