servlet
package com.sxr; import javax.net.ssl.SSLException; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; public class HTTPUtil { private final static int CONNECT_TIME_OUT = 30000; private final static int READ_OUT_TIME = 50000; private static String boundaryString = getBoundary(); public static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> 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<String, String> 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<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) 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; } }
FaceUtil
package com.sxr; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Properties; public class FaceUtil { private static HashMap<String, String> map = new HashMap<>(); static { //读取配置文件当中的内容 Properties pro = new Properties(); InputStream in = FaceUtil.class.getResourceAsStream("/api.properties"); try { pro.load(in); map.put("api_key", pro.getProperty("API_KEY")); map.put("api_secret", pro.getProperty("API_SECRET")); map.put("display_name", pro.getProperty("DISPLAY_NAME")); map.put("outer_id", pro.getProperty("OUTER_ID")); } catch (IOException e) { System.out.println("配置文件读取错误"); throw new RuntimeException(e); } } /** * 查询指定的人脸是否在人脸集合faceset中存在 * * @param * @return * @throws Exception */ public static boolean getDetail() throws Exception { String url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/getdetail"; byte[] bacd = HTTPUtil.post(url, map, null); //符合json格式的字符串 String str = new String(bacd); //转换为json对象 System.out.println(str); if (str.indexOf("error_message") != -1) { return false; } return true; } public static boolean createFaceset() throws Exception { String url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/create"; byte[] bacd = HTTPUtil.post(url, map, null); //符合json格式的字符串 String str = new String(bacd); //转换为json对象 System.out.println(str); if (str.indexOf("error_message") != -1) { return false; } return true; } public static boolean addFace(String faceToken) throws Exception { boolean res = getDetail();//先查询是否有知道的人脸集合 if (!res) {//如果没有就创建 res = createFaceset(); if (res) { return false; } } String url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/addface"; map.put("face_tokens", faceToken); byte[] bacd = HTTPUtil.post(url, map, null); //符合json格式的字符串 String str = new String(bacd); //转换为json对象 System.out.println(str); if (str.indexOf("error_message") != -1) { return false; } return true; } /** * 查询指定的人脸是否在人脸集合faceset中存在 * * @param faceToken * @return * @throws Exception */ public static boolean search(String faceToken) throws Exception { String url = "https://api-cn.faceplusplus.com/facepp/v3/search"; map.put("face_token", faceToken); byte[] bacd = HTTPUtil.post(url, map, null); //符合json格式的字符串 String str = new String(bacd); //转换为json对象 System.out.println(str); if (str.indexOf("error_message") != -1) { return false; } //转换为json对象 JSONObject jsonObject = JSONObject.parseObject(str); JSONObject thresholdsObject = (JSONObject) jsonObject.get("thresholds"); double le5 = thresholdsObject.getDoubleValue("le-5"); //十万分之一的误信率阈值 JSONArray resArr = (JSONArray) jsonObject.get("results"); if (resArr != null && resArr.size() >= 1) { JSONObject res = (JSONObject) resArr.get(0); //取出数组中第一个对象 double confidence = res.getDoubleValue("confidence"); if (confidence > le5) { return true; } } return false; } /** * 根据传入的图片进行人脸检测 * * @param file 传入人脸图片 * @return 返回人脸照片,如果为空,说明图片有问题 */ public static String detect(File file) throws Exception { byte[] buff = HTTPUtil.getBytesFromFile(file); String url = "https://api-cn.faceplusplus.com/facepp/v3/detect"; HashMap<String, byte[]> byteMap = new HashMap<>(); // 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); byte[] bacd = HTTPUtil.post(url, map, byteMap); //符合json格式的字符串 String str = new String(bacd); //转换为json对象 System.out.println(str); if (str.indexOf("error_message") != -1) { System.out.println("请求发生错误"); return null; } JSONObject jsonObject = JSONObject.parseObject(str); int num = jsonObject.getIntValue("face_num"); if (num == 1) { JSONArray array = (JSONArray) jsonObject.get("faces"); JSONObject face = (JSONObject) array.get(0); String faceToken = face.getString("face_token"); return faceToken; } return null; } }
HTTPUtil
package com.sxr; import javax.net.ssl.SSLException; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; public class HTTPUtil { private final static int CONNECT_TIME_OUT = 30000; private final static int READ_OUT_TIME = 50000; private static String boundaryString = getBoundary(); public static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> 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<String, String> 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<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) 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; } }
TestMain
package com.sxr;
import java.io.*;
public class TestMain {
public static void main(String[] args) {
// File file = new File("C:\\Users\\双休日\\Desktop\\image_file\\a22.jpg");
// try {
// String faceToken = FaceUtil.detect(file);
// System.out.println(faceToken);
// boolean res = FaceUtil.search(faceToken);
// System.out.println("查找结果:" + res);
// FaceUtil.addFace(faceToken);
// res = FaceUtil.search(faceToken);
// System.out.println("查找结果:" + res);
//// boolean res = FaceUtil.getDetail();
//// System.out.println("查找结果:" + res);
//// if (res == false) {
//// res = FaceUtil.createFaceset();
//// System.out.println("创建的faceset--outer_id:test"+res);
//// }
//// res = FaceUtil.getDetail();
//// System.out.println("查找结果:" + res);
//
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
File file = new File("C:\\Users\\双休日\\Desktop\\image_file\\a1.jpg");
try {
String str = FaceUtil.detect(file);//人脸检测
System.out.println("face_token:" + str);
//添加一个人脸到集合中
boolean addRes = FaceUtil.addFace(str);
System.out.println("添加结果:" + addRes);
boolean res = FaceUtil.search(str);//人脸搜索
System.out.println("搜索结果:" + res);
//获取人脸的集合
// res = FaceUtil.getDetail();
// if (!res) {//如果没有该集合,就创建一个
// res = FaceUtil.createFaceset();
// System.out.println("如果么有指定的人脸集合,则创建新的");
// }
// System.out.println("outer_id为linaFaceset的人脸集合:" + res);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
aip.properties
API_KEY=自己的key API_SECRET=自己的value DISPLAY_NAME=FaceSet OUTER_ID=FaceSet
标签:旷视,人脸识别,return,String,代码,conne,obos,new,out From: https://www.cnblogs.com/uninan/p/17437318.html