下面我为大家展示一下我调用阿里云人脸识别接口的示例
首先说下开发环境,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 {
@Autowired
private 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-SHA1
String signature = HMACSha1(stringToSign, faceRecognConfig.getAk_secret());
// 3.得到 authorization header
String 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", authH