java Face++ 后台工具类的封装

package com.example.demo.config;



import javax.net.ssl.SSLException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author zhenglong
 * @Description:face++工具类
 * @Date 2020/6/3 23:09
 */
public class FaceUtils {

    private static String APIKEY = "Y1ASgzOuFbt1TwcmHlyBnp8QBIvJxAma";
    private static String SCREAT = "HAGFlf0EDq5GUzJxCt_2QLcx-dGl3KwC";
    private static String FALG = "USERFLAGLLZ";
    private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();


    public void addFace( String faceToken) {
        String url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/addface";
        HashMap map = new HashMap<>();
        HashMap byteMap = new HashMap<>();
        map.put("api_key", APIKEY);
        map.put("api_secret", SCREAT);
        map.put("outer_id", FALG);
        map.put("face_tokens", faceToken);
        try {
            post(url, map, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void createFace() {
        String url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/create";
        HashMap map = new HashMap<>();
        HashMap byteMap = new HashMap<>();
        map.put("api_key", APIKEY);
        map.put("api_secret", SCREAT);
        map.put("outer_id", FALG);
        try {
            post(url, map, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public    String detected(String URL) {

        File file = new File(URL);
        String str = "";
        byte[] buff = getBytesFromFile(file);
        //detect 人脸比对
        String url = "https://api-cn.faceplusplus.com/facepp/v3/detect";
        HashMap map = new HashMap<>();
        HashMap byteMap = new HashMap<>();
        map.put("api_key", APIKEY);
        map.put("api_secret", SCREAT);
        map.put("return_landmark", "1");
        map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
        byteMap.put("image_file", buff);
        try {
            byte[] bacd = post(url, map, byteMap);
            str = new String(bacd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public String searchface(String URL) {
        File file = new File(URL);
        String str = "";
        byte[] buff = getBytesFromFile(file);
        //detect 人脸比对
        String url = "https://api-cn.faceplusplus.com/facepp/v3/search";
        HashMap map = new HashMap<>();
        HashMap byteMap = new HashMap<>();
        map.put("api_key", APIKEY);
        map.put("api_secret", SCREAT);
        map.put("outer_id", FALG);
        byteMap.put("image_file", buff);
        try {
            byte[] bacd = post(url, map, byteMap);
            str = new String(bacd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    protected static byte[] post(String url, HashMap map, HashMap fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\r\n");
            obos.writeBytes("Content-Disposition: form-data; name=\"" + key
                    + "\"\r\n");
            obos.writeBytes("\r\n");
            obos.writeBytes(value + "\r\n");
        }
        if (fileMap != null && fileMap.size() > 0) {
            Iterator fileIter = fileMap.entrySet().iterator();
            while (fileIter.hasNext()) {
                Map.Entry fileEntry = (Map.Entry) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\r\n");
                obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + encode(" ") + "\"\r\n");
                obos.writeBytes("\r\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\r\n");
            }
        }
        obos.writeBytes("--" + boundaryString + "--" + "\r\n");
        obos.writeBytes("\r\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try {
            if (code == 200) {
                ins = conne.getInputStream();
            } else {
                ins = conne.getErrorStream();
            }
        } catch (SSLException e) {
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while ((len = ins.read(buff)) != -1) {
            baos.write(buff, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    }

    private static String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 32; ++i) {
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        }
        return sb.toString();
    }

    private static String encode(String value) throws Exception {
        return URLEncoder.encode(value, "UTF-8");
    }

    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }


}

 

你可能感兴趣的:(后台)