face++api请求

实训第一周,本文介绍了如何使用Face++ API。请求URL存储在api.java的static字段中,密钥和secret_key位于key.java。为方便日期与响应对应,创建了stamp_struct类,包含JSONObject和String。通过request_json.java的get_analyse和get_json方法可实现脸部分析和图片识别。
摘要由CSDN通过智能技术生成

实训第一周,下面我为大家介绍face++api的使用方式。


首先,要明确自己的请求信息也要存在哪里。

请求url存在post_and_request包中的api.java文件中,利用static 字段,让其他class调用不需要实例化api类


package post_and_request;

public class api {
	public static String analysis_api_url="https://api-cn.faceplusplus.com/facepp/v3/face/analyze";
	public static String face_detection_url="https://api-cn.faceplusplus.com/facepp/v3/detect";
}

密钥和secret_key存在里一个叫key的包中的key.java中

package key;

public class key {
	/*String usr="";
	//String passwd="";*/
	//String key="";
	public static String key="pRgMw7ofSgs76wVaq9pL9PYNvuR6zkX_";
	public static String Secret="nQEkilOV_hlhbhgtEj3USO05cw7VN7TM";
}

由于需要date和调用结果对应起来,创建stamp_struct类,存储一个JSONObject和一个String

package request;


import org.json.JSONObject;


public class stamp_struct {
        public String date;
        public JSONObject jsonobject;
        public stamp_struct(String date,JSONObject jsonobject)
        {
                this.date=date;
                this.jsonobject=jsonobject;
        }
        public String toString()
        {
             return ""+date+":"+jsonobject.toString();
        }
}


下面构造一个类

request_json.java

只用调用get_analyse就可以对脸部进行分析,调用get_json就可以对一张图片进行识别。

package request;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.net.ssl.SSLException;


public class request_json {
	private final static int CONNECT_TIME_OUT = 30000;
	//超时时间
    private final static int READ_OUT_TIME = 50000;
    public String get_analyse(ArrayList<String> list,String url,String key,String k_secret)
    {
    	//传入face_token,在发送到远程服务器进行分析
    	HashMap<String, String> map = new HashMap<>();
    	//传入密钥
    	map.put("api_key", key);
    	//传入secret_Key
        map.put("api_secret", k_secret);
		String face_token="";
		for(int m=0;m<list.size();m++)
		{
			if(m<(list.size()-1))
			{
				face_token+=list.get(m)+",";
			}
			if(m==list.size()-1)
			{
				face_token+=list.get(m);
			}
		}
		map.put("face_tokens",face_token);
		map.put("return_landmark", "1");
		//返回什么参数
		map.put("return_attributes", "gender,age,"
         		+ "smiling,headpose,facequality,"
         		+ "blur,eyestatus,emotion,"
         		+ "ethnicity,beauty,mouthstatus,"
         		+ "eyegaze,skinstatus");
		try{
			//尝试将图片传到远程服务器上
            byte[] bacd = post(url, map);
            //将传回的字节变成String
            String str = new String(bacd);
            //返回str
            return str;
            //System.out.println(str);
        }catch (Exception e) {
        	//如果出错,打印出错误信息
        	e.printStackTrace();
		}
		//如果没有正确传递回来的参数的话,返回空值
    	return "";
    }
    public String get_json(String path,String url,String key,String k_secret)
    {
    	 File file = new File(path);
    	 //传入要处理 的图片
 		 byte[] buff = getBytesFromFile(file);
 		 //传入要访问的url
 		 //String url = api.face_detection_url;
         HashMap<String, String> map = new HashMap<>();
         HashMap<String, byte[]> byteMap = new HashMap<>();
         map.put("api_key", key);
         map.put("api_secret", k_secret);
         //识别多少关键点
 		 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);
             //得到结果
             String str = new String(bacd);
             return str;
             //System.out.println(str);
         }catch (Exception e) {
         	e.printStackTrace();
 		}
         return "";
    }

	protected byte[] post(String url, HashMap<String, String> map) throws Exception {
		//进行url连接
		HttpURLConnection conne;
		URL url1 = new URL(url);
		String boundaryString = getBoundary();
		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");
		}
		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;
	}
    protected byte[] post(String url, HashMap<String, String> map,
    		              HashMap<String, byte[]> fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        String boundaryString = getBoundary();
        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;
    }

    public  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;
    }
    
    private 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 String encode(String value) throws Exception{
        return URLEncoder.encode(value, "UTF-8");
    }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值