下面我为大家展示一下我调用阿里云人脸识别接口的示例

首先说下开发环境,springboot 开发的
org.apache.commons.codec.binary.Base64; 这个主要是用来进行base64编码的
下面贴下部分 pom 依赖

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.9.RELEASE</version>
</parent><dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope>
</dependency>

1.然后贴下所需配置及工具类
application.properties 关键部分配置

#阿里云人脸识别AK配置
ak_id=你的ak_id
ak_secret=你的ak_secret
#人脸对比API接口调用地址
verifyUrl=https://dtplus-cn-shanghai.data.aliyuncs.com/face/verify
#人脸检测API接口调用地址
detectUrl=https://dtplus-cn-shanghai.data.aliyuncs.com/face/detect

然后创建配置工具类

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;@Data
@Configuration
public class FaceRecognConfig {@Value("${ak_id}")private String ak_id; //用户ak@Value("${ak_secret}")private String ak_secret;// 用户ak_secret@Value("${verifyUrl}")private String verifyUrl;// 人脸对比API接口调用地址@Value("${detectUrl}")private String detectUrl;// 人脸检测API接口调用地址
}

这里是其中我使用的两个接口工具类及对应方法

@Data
@Configuration
public class FaceRecognUtil {@Autowiredprivate FaceRecognConfig faceRecognConfig;/*** 人脸检测API接口调用* 发送POST请求* @param img1 传入的图片Base64编码* @return FaceDetectResult* @throws Exception Exception*/public FaceDetectResult faceDetect(String img1) throws Exception {PrintWriter out = null;BufferedReader in = null;String result = "";String body = "{\"type\":\"1\",\"content\":\""+img1+"\"}";int statusCode = 200;try {URL realUrl = new URL(faceRecognConfig.getDetectUrl());/** http header 参数*/String method = "POST";String accept = "application/json";String content_type = "application/json";String path = realUrl.getFile();String date = toGMTString(new Date());// 1.对body做MD5+BASE64加密String bodyMd5 = MD5Base64(body);String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n" + path;// 2.计算 HMAC-SHA1String signature = HMACSha1(stringToSign, faceRecognConfig.getAk_secret());// 3.得到 authorization headerString authHeader = "Dataplus " + faceRecognConfig.getAk_id() + ":" + signature;// 打开和URL之间的连接URLConnection conn = realUrl.openConnection();// 设置通用的请求属性conn.setRequestProperty("accept", accept);conn.setRequestProperty("content-type", content_type);conn.setRequestProperty("date", date);conn.setRequestProperty("Authorization", authHeader);// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);// 获取URLConnection对象对应的输出流out = new PrintWriter(conn.getOutputStream());// 发送请求参数out.print(body);// flush输出流的缓冲out.flush();// 定义BufferedReader输入流来读取URL的响应statusCode = ((HttpURLConnection)conn).getResponseCode();if(statusCode != 200) {in = new BufferedReader(new InputStreamReader(((HttpURLConnection)conn).getErrorStream()));} else {in = new BufferedReader(new InputStreamReader(conn.getInputStream()));}String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {e.printStackTrace();} finally {try {if (out != null) {out.close();}if (in != null) {in.close();}} catch (IOException ex) {ex.printStackTrace();}}if (statusCode != 200) {throw new IOException("\nHttp StatusCode: "+ statusCode + "\nErrorMessage: " + result);}return JsonUtil.readValue(result, FaceDetectResult.class);}/*** 人脸对比API接口调用* 发送POST请求* @param img1 传入的图片base64编码* @param img2 传入的图片base64编码* @return* @throws Exception Exception*/public FaceVerifyResult faceVerify(String img1, String img2) throws Exception {PrintWriter out = null;BufferedReader in = null;String result = "";String body = "{\"type\":\"1\",\"content_1\":\""+img1+"\",\"content_2\":\""+img2+"\"}";int statusCode = 200;try {URL realUrl = new URL(faceRecognConfig.getVerifyUrl());/** http header 参数*/String method = "POST";String accept = "application/json";String content_type = "application/json";String path = realUrl.getFile();String date = toGMTString(new Date());// 1.对body做MD5+BASE64加密String bodyMd5 = MD5Base64(body);String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n" + path;// 2.计算 HMAC-SHA1String signature = HMACSha1(stringToSign, faceRecognConfig.getAk_secret());// 3.得到 authorization headerString authHeader = "Dataplus " + faceRecognConfig.getAk_id() + ":" + signature;// 打开和URL之间的连接URLConnection conn = realUrl.openConnection();// 设置通用的请求属性conn.setRequestProperty("accept", accept);conn.setRequestProperty("content-type", content_type);conn.setRequestProperty("date", date);conn.setRequestProperty("Authorization", authHeader);// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);// 获取URLConnection对象对应的输出流out = new PrintWriter(conn.getOutputStream());// 发送请求参数out.print(body);// flush输出流的缓冲out.flush();// 定义BufferedReader输入流来读取URL的响应statusCode = ((HttpURLConnection)conn).getResponseCode();if(statusCode != 200) {in = new BufferedReader(new InputStreamReader(((HttpURLConnection)conn).getErrorStream()));} else {in = new BufferedReader(new InputStreamReader(conn.getInputStream()));}String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {e.printStackTrace();} finally {try {if (out != null) {out.close();}if (in != null) {in.close();}} catch (IOException ex) {ex.printStackTrace();}}if (statusCode != 200) {throw new IOException("\nHttp StatusCode: "+ statusCode + "\nErrorMessage: " + result);}return JsonUtil.readValue(result, FaceVerifyResult.class);}/*** 计算MD5+BASE64* @param s 需要加密的字符串* @return 加密之后的字符串*/String MD5Base64(String s) {if (s == null)return null;String encodeStr = "";byte[] utfBytes = s.getBytes();MessageDigest mdTemp;try {mdTemp = MessageDigest.getInstance("MD5");mdTemp.update(utfBytes);byte[] md5Bytes = mdTemp.digest();encodeStr = Base64.encodeBase64String(md5Bytes);} catch (Exception e) {throw new Error("Failed to generate MD5 : " + e.getMessage());}return encodeStr;}/*** 计算 HMAC-SHA1* @param data stringToSign* @param key ak_secret* @return HMAC-SHA1*/String HMACSha1(String data, String key) {String result;try {SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");Mac mac = Mac.getInstance("HmacSHA1");mac.init(signingKey);byte[] rawHmac = mac.doFinal(data.getBytes());result = Base64.encodeBase64String(rawHmac);} catch (Exception e) {throw new Error("Failed to generate HMAC : " + e.getMessage());}return result;}/*** 等同于javaScript中的 new Date().toUTCString();* @param date 时间* @return 格式化之后的时间*/String toGMTString(Date date) {SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));return df.format(date);}/*** 这个是阿里的demo方法* @param url 接口调用的地址* @param body 接口传入的参数* @param ak_id 你的ak_id* @param ak_secret 你的ak_secret* @return String 响应结果* @throws Exception 抛出的异常*/public String sendPost(String url, String body, String ak_id, String ak_secret) throws Exception {PrintWriter out = null;BufferedReader in = null;String result = "";int statusCode = 200;try {URL realUrl = new URL(url);/** http header 参数*/String method = "POST";String accept = "application/json";String content_type = "application/json";String path = realUrl.getFile();String date = toGMTString(new Date());// 1.对body做MD5+BASE64加密String bodyMd5 = MD5Base64(body);String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n" + path;// 2.计算 HMAC-SHA1String signature = HMACSha1(stringToSign, ak_secret);// 3.得到 authorization headerString authHeader = "Dataplus " + ak_id + ":" + signature;// 打开和URL之间的连接URLConnection conn = realUrl.openConnection();// 设置通用的请求属性conn.setRequestProperty("accept", accept);conn.setRequestProperty("content-type", content_type);conn.setRequestProperty("date", date);conn.setRequestProperty("Authorization", authHeader);// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);// 获取URLConnection对象对应的输出流out = new PrintWriter(conn.getOutputStream());// 发送请求参数out.print(body);// flush输出流的缓冲out.flush();// 定义BufferedReader输入流来读取URL的响应statusCode = ((HttpURLConnection)conn).getResponseCode();if(statusCode != 200) {in = new BufferedReader(new InputStreamReader(((HttpURLConnection)conn).getErrorStream()));} else {in = new BufferedReader(new InputStreamReader(conn.getInputStream()));}String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {e.printStackTrace();} finally {try {if (out != null) {out.close();}if (in != null) {in.close();}} catch (IOException ex) {ex.printStackTrace();}}if (statusCode != 200) {throw new IOException("\nHttp StatusCode: "+ statusCode + "\nErrorMessage: " + result);}return result;}
}

下面是两个返回的工具类
1.人脸检测工具类

import lombok.Data;@Data
public class FaceDetectResult {private int errno;// 0为成功,非0为失败,详细说明参见错误码private String err_msg;// 处理失败时的说明private String request_id;// request_id 请求id信息private int face_num;// 检测出来的人脸个数private int[] face_rect;// 返回人脸矩形框,分别是[left, top, width, height], 如有多个人脸,则依次顺延,返回矩形框。如有两个人脸则返回[left1, top1, width1, height1, left2, top2, width2, height2]private float[] face_prob;// 返回人脸概率, 0-1之间,如有多个人脸,则依次顺延。如有两个人脸则返回[face_prob1, face_prob2]private float[] pose;// 返回人脸姿态[yaw, pitch, roll], yaw为左右角度,取值[-90, 90],pitch为上下角度,取值[-90, 90], roll为平面旋转角度,取值[-180, 180],如有多个人脸,则依次顺延private int landmark_num;// 特征点数目,目前固定为105点(顺序:眉毛24点,眼睛32点,鼻子6点,嘴巴34点,外轮廓9点)private float[] landmark;// 特征点定位结果,每个人脸返回一组特征点位置,表示方式为(x0, y0, x1, y1, ……);如有多个人脸,则依次顺延,返回定位浮点数private float[] iris;// 左右两个瞳孔的中心点坐标和半径,每个人脸6个浮点数,顺序是[left_iris_cenpt.x, left_iris_cenpt.y, left_iris_radius, right_iris_cenpt.x, right_iris_cenpt.y, right_iris_radis]
}

2.人脸对比工具类

import lombok.Data;@Data
public class FaceVerifyResult {private int errno;// 0为成功,非0为失败,详细说明参见错误码private String err_msg;// 处理失败时的说明private String request_id;// request_id 请求id信息private float confidence;// 两张图片中最大人脸属于同一个人的置信度:0-100,如某张图片中没有人脸,返回置信度为0private float[] thresholds;// 误识率在10e-3,10e-4,10e-5时对应的置信度分类阈值private int[] rectA;// 图片1最大人脸矩形框(left, top, width, height),如图片中没有人脸,返回矩形框数值均为0private int[] rectB;// 图片2最大人脸矩形框(left, top, width, height),如图片中没有人脸,返回矩形框数值均为0
}

3.JsonUtil 工具类


import java.util.Map;
import java.util.HashMap;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;public class JsonUtil {static ObjectMapper objectMapper;static {if (objectMapper == null) {objectMapper = new ObjectMapper();}//      objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//      objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);// 允许出现特殊字符和转义符objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);objectMapper.configure(Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);// 允许出现单引号objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);objectMapper.configure(Feature.ALLOW_NON_NUMERIC_NUMBERS, true);}/*** 使用泛型方法,把json字符串转换为相应的JavaBean对象。<br/>* (1)转换为普通JavaBean:readValue(json,Student.class)<br/>* (2)转换为List:readValue(json,List.class).但是如果我们想把json转换为特定类型的List,比如List<Student>,就不能直接进行转换了。* 因为readValue(json,List.class)返回的其实是List<Map>类型,你不能指定readValue()的第二个参数是List<Student>.class,所以不能直接转换。* 我们可以把readValue()的第二个参数传递为Student[].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List。<br/>*  (3)转换为Map:readValue(json,Map.class) 我们使用泛型,得到的也是泛型<br/>* @param content 要转换的JavaBean类型* @param valueType 原始json字符串数据* @return JavaBean对象*/public static <T> T readValue(String content, Class<T> valueType) {if (StringUtils.isEmpty(content) || StringUtils.isEmpty(valueType)) {return null;}try {return objectMapper.readValue(content, valueType);} catch (Exception e) {return null;}}
}

最后是测试,还是不废话,直接上代码

@RestController
public class CyryManagerController {@Autowiredprivate FaceRecognConfig faceRecognConfig;@Autowiredprivate FaceRecognUtil faceRecognUtil;@GetMapping(value = "/test")public String tes(String img,String img1) throws Exception {// 人脸检测调用FaceDetectResult fDetectResult = faceRecognUtil.faceDetect(img);System.out.println(fDetectResult.toString());// 人脸对比调用FaceVerifyResult fVerifyResult = faceRecognUtil.faceVerify(img,img1);System.out.println(fVerifyResult.toString());}
}

调用阿里云人脸识别接口示例相关推荐

  1. 阿里云人脸识别接口调用卡顿,超时

    阿里云人脸识别接口调用卡顿 在服务端通过pom引入阿里云人脸识别sdk的时候,如果生产环境在内网开通了网络策略连接了 cloudauth.aliyuncs.com 这个地址. 但是sdk调用人脸识别服 ...

  2. 阿里云人脸识别接口--心得分享

    一:对接阿里云人脸识别接口的工具类 注意:如果你的图片已经转换为base64的编码以后参数是content_1,后面要加type请求参数,我这里是通过图片的url对比的 public class Fa ...

  3. 阿里云人脸识别C#调用示例参考

    概述 前面介绍了关于阿里云人脸识别Java调用示例参考,本文主要介绍C#调用阿里云人脸识别服务,参数等的获取参考阿里云人脸识别使用流程简介. Code Sample 1.使用网络图片 using Sy ...

  4. 阿里云人脸识别C#调用示例参考 1

    概述 前面介绍了关于阿里云人脸识别Java调用示例参考,本文主要介绍C#调用阿里云人脸识别服务,参数等的获取参考阿里云人脸识别使用流程简介. Code Sample 1.使用网络图片 using Sy ...

  5. 阿里云人脸识别PHP调用示例参考

    概述 前面分别给出了关于阿里云人脸识别Java调用示例参考.阿里云人脸识别C#调用示例参考.阿里云人脸识别Python3调用示例参考 .本文主要介绍PHP调用阿里云人脸识别服务,参数等的获取参考阿里云 ...

  6. 百度云人脸识别接口+python+opencv做的表情包合成器

    第一次使用python,所以语法有些凌乱. 菜鸟随便做的一个小东西. 开发环境:win10+anaconda3.0+python3.6+opencv2+pyqt5 一.anaconda安装 下载链接: ...

  7. 阿里云人脸识别公测使用说明

    概述 之前阿里云人脸识别只提供人脸检测,人脸属性及人脸对比三个API接口,关于这方面的介绍及使用细节,可以参考阿里云人脸识别使用流程简介,之前使用的服务地址为:dtplus-cn-shanghai.d ...

  8. 阿里云人脸识别使用流程简介

    概述 之前写过一篇关于Java 使用阿里云人脸识别的博客,介绍了如何使用网络及本地图片基于Rest API调用人脸识别服务.实际的使用中发现很多用户因为之前没有使用过人脸识别,对前期的一些参数配置还是 ...

  9. 使用java调用阿里云车牌识别API

    实现车牌识别功能我采用调用阿里云车牌识别API的方法,我使用的是eclipse,jdk 1.8,Tomcat 9.0 1.进入阿里云主页先创建阿里云账号 2.在控制台的头像那里找到AccessKey管 ...

最新文章

  1. Could not find the main class: org.apache.catalina.startup.Boostrap. Program will exit.
  2. 腾讯云+未来高峰对话:智能+时代的创新与探索
  3. 【Linux入门到精通系列讲解】内存管理malloc和free函数
  4. Python Profiler 列举
  5. 简明Python3教程 17.更多
  6. php自定义按钮,vue实现自定义按钮的方法介绍(附代码)
  7. LOJ#6038. 「雅礼集训 2017 Day5」远行(LCT)
  8. java商城系统设计-----积分商城系统
  9. 黑客使用浏览器中的浏览器技术窃取Steam凭证
  10. multisim14安装与卸载
  11. 佳能mp236打印机驱动 官方版
  12. 华为铁三角作战的道法术,华为铁三角第一人,LTC专家许浩明老师讲授
  13. Namenode处于安全模式时,对hadoop进行查看操作,edits_inprogress_txid中没有事物事件的增加,txid没有增加?
  14. 程序员技术等级评定职称详细介绍
  15. 通过cv2.VideoCapture完成跳帧截取视频图片
  16. 重置IDEA,将原来的设置清除
  17. Day of Week
  18. matlab 使得三维图形可以手动旋转,三维图形的平移,旋转与错切
  19. 小孔成像总结_初中物理解题技巧+方法总结,非常实用,初二初三都要看!
  20. android lottie字体json,从json文件到炫酷动画-Lottie实现思路和源码分析

热门文章

  1. mysql获取字符串第2次出现的位置_我要获取一个字符串中某个标点第二次出现的位置...
  2. 事前多思考,事后多总结,做事多用心,事事都开心
  3. 谈谈Q+平台的技术实现
  4. 最小生成树 - Prim算法
  5. 利用自监督学习的放端故事生成评价方法
  6. Android获取整个屏幕的Touch事件
  7. 复合索引的优点和注意事项
  8. css动画小案例 弹力球
  9. css 右上角 翻开动画_27个精致的CSS3动画效果源代码下载
  10. 老杨说运维 | 2021GOPS全球运维大会 上海站擎创CEO杨辰演讲精选(二)