赞
踩
链接
详细内容查看官方文档
https://cloud.baidu.com/product/face
获取AccessToken
接口
public interface BaiDuAccessTokenService { /** * 获取权限token * @return 返回示例: * { * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567", * "expires_in": 2592000 * } */ public String getAuth(); /** * * 获取API访问的token * 该token有一定的有效期,需要自行管理,当失效时需重新获取. * @param ak - 百度云官网获取的 API Key * @param sk - 百度云官网获取的 Securet Key */ public void getAuth(String ak, String sk);
实体类,为了设置期限,我们封装一个实体类,其中定义一个
public boolean isExpired()
方法,用于查看是否过期,这里我们set方法和构造方法都经过了修改,
public class BaiDuAccessToken { private String accessToken; private long expires_time; public BaiDuAccessToken(String accessToken) { this.accessToken = accessToken; this.expires_time = System.currentTimeMillis() + 2592000 * 1000L; } public BaiDuAccessToken() { } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public long getExpires_time() { return expires_time; } // 一个月的时间过期 public void setExpires_time() { this.expires_time = System.currentTimeMillis() + 2592000 * 1000L; } public boolean isExpired() { return System.currentTimeMillis() > expires_time; } }
Impl,我们需要获得accesstoken时,就调用该类,使用无参的public String getAuth()
,其会根据过期时间自动化判断是否需要获取access_token,无需人工干预
@Service public class BaiDuAccessTokenServiceImpl implements BaiDuAccessTokenService { //构建一个baiDuAccessToken对象,从而提升运行速度,避免每次都发送请求 private static BaiDuAccessToken baiDuAccessToken = new BaiDuAccessToken(); // 官网获取的 API Key 更新为你注册的 private String clientId = "官网的API Key"; // 官网获取的 Secret Key 更新为你注册的 private String clientSecret = "官网的 Secret Key"; // 调用该类,获取accesstoken时的方法 @Override public String getAuth() { if (baiDuAccessToken == null || baiDuAccessToken.isExpired()){ getAuth(clientId,clientSecret); } return baiDuAccessToken.getAccessToken(); } @Override public void getAuth(String ak, String sk) { // 获取token地址 String authHost = "https://aip.baidubce.com/oauth/2.0/token?"; String getAccessTokenUrl = authHost // 1. grant_type为固定参数 + "grant_type=client_credentials" // 2. 官网获取的 API Key + "&client_id=" + ak // 3. 官网获取的 Secret Key + "&client_secret=" + sk; try { URL realUrl = new URL(getAccessTokenUrl); // 打开和URL之间的连接 HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); connection.setRequestMethod("GET"); connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.err.println(key + "--->" + map.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String result = ""; String line; while ((line = in.readLine()) != null) { result += line; } System.err.println("百度access_token获取的result:" + result); JSONObject jsonObject = JSONObject.parseObject(result); String access_token = jsonObject.getString("access_token"); // 给baiDuAccessToken赋值 baiDuAccessToken.setAccessToken(access_token); baiDuAccessToken.setExpires_time(); } catch (Exception e) { System.err.printf("获取token失败!"); e.printStackTrace(System.err); } } }
接口
public interface FaceDetectService {
/**
* 发送请求,获取人脸信息
* @param faceDetectReq
* @return
*/
public String getFaceInfo(FaceDetectReq faceDetectReq);
}
注意我们的请求参数的设置,文档中我们需要发送post请求,设置URL、Header以及请求Json,这需要用到HttpHeaders设置header, URIBuilder组合URL,fastjson格式化实体类,RestTemplate发送请求,并整合URL、Header以及JSON
实体类,这是我们请求参数的封装类,不是返回参数的封装,返回参数封装比较繁琐,这里不再赘述。我们使用BASE64作为图片参数,(因为微信公众号平台的图片链接,百度AI无法直接解析,需要转为BASE64)
public class FaceDetectReq { private String image; private String image_type="BASE64"; private long max_face_num = 10L ; public long getMax_face_num() { return max_face_num; } // 主流的备选信息age,beauty,expression,face_shape,gender,glasses private String face_field="age,beauty,expression,face_shape,gender,glasses"; public FaceDetectReq() { } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getImage_type() { return image_type; } public String getFace_field() { return face_field; } // 将image的信息设置为url地址 public FaceDetectReq(String base64) { image = base64; } }
Impl
@Service public class FaceDetectServiceImpl implements FaceDetectService { BaiDuAccessTokenServiceImpl accessTokenService = new BaiDuAccessTokenServiceImpl(); //请求的URL final String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"; final String access_token = accessTokenService.getAuth(); @Override public String getFaceInfo(FaceDetectReq faceDetectReq) { //设置header HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); httpHeaders.set("Content-Type","application/json"); //对象转为jsonObject JSONObject jsonObject = new JSONObject(); String params = jsonObject.toJSONString(faceDetectReq); jsonObject = JSONObject.parseObject(params); //设置URL URIBuilder uriBuilder = null; try { uriBuilder = new URIBuilder(url); uriBuilder.addParameter("access_token",access_token); System.out.println(uriBuilder); } catch (URISyntaxException e) { e.printStackTrace(); } //发送post请求携带header以及json HttpEntity httpEntity = new HttpEntity(jsonObject,httpHeaders); RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.postForObject(uriBuilder.toString(),httpEntity,String.class); return result; } }
大体上,我们已经实现了业务层的编码工作,部署到公众号还需有个人的域名、服务器、以及掌握json转xml、封装百度ai返回值这些技能,如果有兴趣,可以再出一篇博客。
这里贴上几张测试图,也欢迎大家来公众号玩一玩这个人脸识别的功能。(返回格式可能会有变化,功能也会逐渐完善)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。