package com.example.demo;
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;
/**
* @auther: LiChaoChao
* @date: 2019-03-12
*/
public class FaceTest {
public static void main(String[] args) throws Exception {
File file = new File("/Users/smkk/face/src/main/resources/lcc.jpeg");
byte[] buff = getBytesFromFile(file);
String url = "https://api-cn.faceplusplus.com/facepp/v3/detect";
HashMap<String, String> map = new HashMap<>();
HashMap<String, byte[]> byteMap = new HashMap<>();
map.put("api_key", "_QwmPsTRZ0BEe6KHBMbxu04v91OjwMOb");
map.put("api_secret", "EGpglw4Lr8xfFjfD3VfpmMs7b9CLMflV");
map.put("return_landmark", "0");//0-不检测 1-检测,返回83个人脸关键点 2-检测,返回106个人脸关键点。
// gender-性别
// age-年龄
// smiling-微笑值[0,100],阈值50[超过阈值认为是笑脸]
// emotion-情绪[anger:愤怒 disgust:厌恶 fear:恐惧 happiness:高兴 neutral:平静 sadness:伤心 surprise:惊讶]
// beauty- 颜值[0,100]分为[male_score, female_score]
map.put("return_attributes", "gender,age,smiling,emotion,beauty");
byteMap.put("image_file", buff);
try {
byte[] bacd = post(url, map, byteMap);
String str = new String(bacd);
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
private final static int CONNECT_TIME_OUT = 30000;
private final static int READ_OUT_TIME = 50000;
private static String boundaryString = getBoundary();
private static byte[] post(String urlStr, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setConnectTimeout(CONNECT_TIME_OUT);
con.setReadTimeout(READ_OUT_TIME);
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
DataOutputStream obos = new DataOutputStream(con.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 = con.getResponseCode();
try {
if (code == 200) {
ins = con.getInputStream();
} else {
ins = con.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();
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
for (int i = 0; i < 32; ++i) {
sb.append(chars.charAt(random.nextInt(chars.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;
}
}