使用百度Ai进行人脸身份识别(公安验证)

import com.baidu.aip.util.Base64Util;

import com.enation.app.base.core.service.Exception.CreditAuthFaceException;

import com.enation.app.base.core.service.ICreditAuthManager;

import com.enation.app.base.core.util.AuthTokenService;

import com.enation.app.base.core.util.HttpClientUtils;

import org.apache.http.client.methods.CloseableHttpResponse;

import java.io.*;

import javax.imageio.stream.FileImageInputStream;

import javax.imageio.stream.FileImageInputStream;

import java.net.HttpURLConnection;

import java.net.URLEncoder;

import java.util.HashMap;

import java.util.Map;


/**

* 人脸识别service

* @param name

* @param id_card

* @param faceUrl

*/

@Override

public void face(String name, String id_card, String faceUrl) {

//调用接口获取tocken(有效期一个月)

    String token = AuthTokenService.getAuth();

System.out.println("1:token:" + token);

//调用身份验证api地址

    String url ="https://aip.baidubce.com/rest/2.0/face/v2/person/verify?access_token=" + token;

File face=new File(faceUrl);

FileImageInputStream input =null;

byte[] data =null;

String base64Image =null;

try {

input =new FileImageInputStream(face);

ByteArrayOutputStream output =new ByteArrayOutputStream();

byte[] buf =new byte[1024];

int numBytesRead =0;

while ((numBytesRead = input.read(buf)) != -1) {

output.write(buf,0, numBytesRead);

}

data = output.toByteArray();

base64Image = Base64Util.encode(data);

System.out.println("4base64转码:"+base64Image);

}catch (IOException e) {

e.printStackTrace();

}finally {

try {

if (input !=null) {

input.close();

}

}catch (IOException e) {

e.printStackTrace();

}

}

Map headers =new HashMap();

headers.put("Content-Type","application/x-www-form-urlencoded");

Map bodys =new HashMap();

bodys.put("image", base64Image);

bodys.put("id_card_number", id_card);

bodys.put("name", name);

try {

CloseableHttpResponse response = HttpClientUtils.doHttpsPost(url, headers, bodys);

String result= HttpClientUtils.toString(response);

System.out.println("5返回json数据:" + result);

org.json.JSONObject jsonObject=new org.json.JSONObject(result);

System.out.println("jsonObject:"+jsonObject);

Object jsonResult = jsonObject.get("result");

Float floatResult = Float.parseFloat(jsonResult.toString());

if (floatResult >=0.80) {

System.out.println("floatResult:"+floatResult+"人脸身份验证成功");

}else {

System.out.println("floatResult:"+floatResult+"人脸身份验证失败");

throw new CreditAuthFaceException("人脸身份验证失败");

}

}catch (Exception e) {

e.printStackTrace();

System.out.println("异常输出");

throw new CreditAuthFaceException("人脸认证失败");

}

}

你可能感兴趣的:(使用百度Ai进行人脸身份识别(公安验证))