创建百度工程
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);
// }
}
}