アリ雲の顔認識インタフェースの例を呼び出す


アリ雲の顔認識インタフェースを呼び出した例を示します
まず開発環境,springboot開発のorgについて述べる.apache.commons.codec.binary.Base64; これは主にbase 64符号化を行うための以下のpom依存性の一部である.

	org.springframework.boot
	spring-boot-starter-parent
	1.5.9.RELEASE



	commons-codec
	commons-codec


  	org.projectlombok
    lombok
    provided


1.必要な構成およびツールクラスアプリケーションを貼り付ける.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      
}


ここでは、私が使用している2つのインタフェースツールクラスと対応方法について説明します.
@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 + "
" + accept + "
" + bodyMd5 + "
" + content_type + "
" + date + "
" + 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", 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("
Http StatusCode: "+ statusCode + "
ErrorMessage: " + 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 + "
" + accept + "
" + bodyMd5 + "
" + content_type + "
" + date + "
" + 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", 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("
Http StatusCode: "+ statusCode + "
ErrorMessage: " + 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 + "
" + accept + "
" + bodyMd5 + "
" + content_type + "
" + date + "
" + path; // 2. HMAC-SHA1 String signature = HMACSha1(stringToSign, ak_secret); // 3. authorization header String 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("
Http StatusCode: "+ statusCode + "
ErrorMessage: " + result); } return result; } }

次に、返される2つのツールクラス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,          ,      0
	private float[] thresholds;//     10e-3,10e-4,10e-5           
	private int[] rectA;//   1       (left, top, width, height),        ,         0
	private 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  。
* (1) JavaBean:readValue(json,Student.class)
* (2) List:readValue(json,List.class). json List, List, 。 * readValue(json,List.class) List , readValue() List.class, 。 * readValue() Student[].class. Arrays.asList(); List。
* (3) Map:readValue(json,Map.class) ,
* @param content JavaBean * @param valueType json * @return JavaBean */ public static T readValue(String content, Class 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 {
	@Autowired
	private FaceRecognConfig faceRecognConfig;
	
	@Autowired
	private 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());
	}
}