二要素/三要素/face++/人脸识别-第三接口的调用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011277745/article/details/88872610
package com.yinker.datacenter.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.yinker.datacenter.entity.common.GeoApiFlagEnum;
import com.yinker.datacenter.utils.HttpClientUtils;
import com.yinker.datacenter.utils.IdGenerator;
import com.yinker.datacenter.utils.Json2MapUtil;
import com.yinker.datacenter.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author xuzn
 * @ClassName: ThirdVerifyService
 * @ProjectName user-service
 * @Description: TODO
 * @date 2019/2/15/11:35
 */
@Slf4j
@Service
public class ThirdVerifyService {

    /**
     * 获取集奥验证需要的token,并缓存到redis中
     *
     * @return token
     */
    private String getTokenId() {
        log.info("geo getTokenId 请求token重新登录");
        String token = "";
        String url = ConfigLoadService.configMap.get("geo.verify.url") + ConfigLoadService.configMap.get("geo.verify.url_login");

        try {
            // 通过第三方接口取得key
            log.info("geo 重新开始getTokenId");
            token = getTokenIdLogin();

        } catch (Exception e) {
            log.info("Third.调用登录接口失败url:" + url + " " + e);
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 获取集奥验证需要的token,每次都重新直接请求
     *
     * @return token
     */
    private String getTokenIdLogin() {
        String tokenLogin = "";
        String geoVerifyUrl = ConfigLoadService.configMap.get("geo.verify.url");
        String geoLoginPath = ConfigLoadService.configMap.get("geo.verify.url_login");
        String url = geoVerifyUrl + geoLoginPath;
        try {
            // 通过第三方接口取得key
            log.info("geo 重新开始getTokenId");
            HashMap<String, Object> paramsMap = new HashMap<>();
            String geoUser = ConfigLoadService.configMap.get("geo.verify.user");
            String geoAes2Key = ConfigLoadService.configMap.get("geo.verify.aes");
            String geoPassword = ConfigLoadService.configMap.get("geo.verify.passwd");
            paramsMap.put("username", SecurityUtil.encrypt(geoUser, geoAes2Key));
            paramsMap.put("password", SecurityUtil.encrypt(geoPassword, geoAes2Key));
            String geoUserId = ConfigLoadService.configMap.get("geo.verify.userId");
            paramsMap.put("uno", geoUserId);
            paramsMap.put("encrypted", "1");
            paramsMap.put("dsign", SecurityUtil.encrypt("0", geoAes2Key));
            log.info("调用geo登录,请求url:" + url + getParams(paramsMap));

            Map<String, Object> res = HttpClientUtils.execute(url, paramsMap);

            //解析返回登录第三方结果
            if (res == null) {
                return tokenLogin;
            }
            String strRepose = (String) (res.get("rs"));
            if (Strings.isNullOrEmpty(strRepose)) {
                return tokenLogin;
            }
            log.info("geo 调用登录返回:" + strRepose);
            if (!strRepose.startsWith("{")) {
                strRepose = SecurityUtil.decrypt(strRepose, geoAes2Key);
            }
            log.info("geo 返回解密结果" + strRepose);
            JSONObject jsonObject = JSONObject.parseObject(strRepose);
            tokenLogin = jsonObject.getString("tokenId");
        } catch (Exception e) {
            log.info("Third.直接调用GEO第三方登录接口失败url:" + url + " " + e);
            e.printStackTrace();
        }
        return tokenLogin;
    }

    /**
     * GEO集奥验证接口
     *
     * @param token  api token
     * @param name   姓名
     * @param cardId 身份证号
     * @param mobile 手机号
     * @return
     */
    private HashMap<String, Object> queryUnify(String token, String name, String cardId, String mobile) {
        HashMap<String, Object> retMap = new HashMap<>();
        if (Strings.isNullOrEmpty(token)) {
            log.error("queryUnify token为空");
            retMap.put("code", 1);
            retMap.put("msg", "queryUnify token为空!");
            return retMap;
        }

        HashMap<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("tokenId", token);
        String geoInnerIfType = ConfigLoadService.configMap.get("geo.verify.type");
        String geoAes2Key = ConfigLoadService.configMap.get("geo.verify.aes");
        String geoUserId = ConfigLoadService.configMap.get("geo.verify.userId");
        paramsMap.put("innerIfType", SecurityUtil.encrypt(geoInnerIfType, geoAes2Key));
        paramsMap.put("cid", SecurityUtil.encrypt(mobile, geoAes2Key));
        paramsMap.put("idNumber", SecurityUtil.encrypt(cardId, geoAes2Key));
        paramsMap.put("realName", SecurityUtil.encrypt(name, geoAes2Key));
        String auth = String.valueOf(System.currentTimeMillis() / 1000) + "00" + geoUserId +
                UUID.randomUUID().toString().replace("-", "");
        paramsMap.put("authCode", SecurityUtil.encrypt(auth, geoAes2Key));

        String url = ConfigLoadService.configMap.get("geo.verify.url") + ConfigLoadService.configMap.get("geo.verify.url_verify");
        try {

            Map<String, Object> res = HttpClientUtils.execute(url, paramsMap);
            log.info("调用geo查询返回:" + res);
            if (res == null || res.get("rs") == null) {
                retMap.put("code", 1);
                retMap.put("msg", "第三方返回数据为空!");
                return retMap;
            }

            String strResponse = (String) (res.get("rs"));
            log.info("geo 调用查询返回:" + strResponse);
            if (Strings.isNullOrEmpty(strResponse)) {
                retMap.put("code", 1);
                retMap.put("msg", "解析第三方数据失败!");
                return retMap;
            }

            if (!strResponse.startsWith("{")) {
                strResponse = SecurityUtil.decrypt(strResponse, geoAes2Key);
            }
            log.info("geo 返回解密结果" + strResponse);

            // 解析返回的结果
            retMap = parseResponse(strResponse);
        } catch (Exception e) {
            log.error("queryUnify Exception:" + e);
        }
        return retMap;
    }

    /**
     * 拼接请求参数
     *
     * @param maps
     * @return
     */
    private String getParams(HashMap<String, Object> maps) {
        StringBuilder strParams = new StringBuilder();
        int i = 0;
        for (String key : maps.keySet()) {
            i++;
            strParams.append(key).append("=").append(maps.get(key));
            if (i == maps.size()) {
                continue;
            }
            strParams.append("&");
        }
        return strParams.toString();
    }

    /**
     * 解析GEO接口返回的结果
     *
     * @param strResponse
     * @return
     */
    private HashMap<String, Object> parseResponse(String strResponse) {
        HashMap<String, Object> result = new HashMap<>();
        JSONObject response = JSONObject.parseObject(strResponse);
        ;
        String code = response.getString("code");

        if (Strings.isNullOrEmpty(code)) {
            log.error("验证三要素不通过,queryUnify无返回code");
            result.put("code", 1);
            result.put("msg", "验证三要素不通过,queryUnify无返回code!");
            return result;
        }

        //需要重新登录
        if (code.equals(GeoApiFlagEnum.STATUS_TOKEN_NULL.getKey())
                || code.equals(GeoApiFlagEnum.STATUS_TOKEN_EXPIRE.getKey())
                || code.equals(GeoApiFlagEnum.STATUS_TOKEN_NEED_LOGIN.getKey())) {
            log.info("geo Token 无效" + code);

            result.put("code", 1);
            result.put("msg", "geo Token 无效,请重新登录!");
            return result;
        }

        if (!code.equals(GeoApiFlagEnum.STATUS_OK.getKey())) {
            result.put("code", 1);
            result.put("msg", response.getString("msg"));
            return result;
        }

        JSONObject data = response.getJSONObject("data");
        JSONArray rslArray = data.getJSONArray("RSL");
        for (Object object : rslArray) {
            JSONObject item = (JSONObject) object;
            // 需要与请求的参数一致
            String geoInnerIfType = ConfigLoadService.configMap.get("geo.verify.type");
            if (!geoInnerIfType.equals(item.getString("IFT"))) {
                continue;
            }
            String subCode = item.getJSONObject("RS").getString("code");
            String subMsg = item.getJSONObject("RS").getString("desc");
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("code", subCode);
            paramMap.put("desc", subMsg);
            if (subCode.equals("0")) {
                result.put("code", 0);
                result.put("msg", "解析数据成功");
                result.put("data", paramMap);
                return result;
            }
        }
        return result;
    }


    /**
     * @param name:用户真实姓名
     * @param cardId:身份证号码
     * @param mobile:手机号
     * @return
     */

    public HashMap<String, Object> verifyThreeElements(String name, String cardId, String mobile) {
        HashMap<String, Object> retMap = new HashMap<>();
        log.info("verifyThreeElements name: " + name + " cardId: " + cardId + " mobile: " + mobile);
        if (Strings.isNullOrEmpty(name) || Strings.isNullOrEmpty(cardId) || Strings.isNullOrEmpty(mobile)) {
            retMap.put("code", 1);
            retMap.put("msg", "用户姓名或者身份证号或者手机号其中一项为空!");
            return retMap;
        }

        try {
            // 没有命中缓存,需要通过接口查询结果
            String key = getTokenId();
            if (Strings.isNullOrEmpty(key)) {
                retMap.put("code", 1);
                retMap.put("msg", "三方接口TOKEN错误!");
                return retMap;
            }
            //验证
            retMap = queryUnify(key, name, cardId, mobile);
            return retMap;
        } catch (Exception e) {
            retMap.put("code", 2);
            retMap.put("msg", "验证过程中发生异常!");
            log.error("verifyThreeElements 异常 " + e);
        }
        return retMap;
    }

    /**
     * @param name:用户真实姓名
     * @param cardId:身份证号码
     * @return
     */

    public HashMap<String, Object> verifyTwoElements(String name, String cardId) {
        HashMap<String, Object> retMap = new HashMap<>();
        log.info("二要素查询 name:" + name + "idcard: " + cardId);
        if (Strings.isNullOrEmpty(name) || Strings.isNullOrEmpty(cardId)) {
            retMap.put("code", 1);
            retMap.put("msg", "用户姓名或者身份证号为空!");
            return retMap;
        }

        try {
            // 不在缓存中,调用接口查询,
            HashMap<String, Object> paramsMap = new HashMap<>();
            String multidataVerifyDesKey = ConfigLoadService.configMap.get("multidata.verify.des");
            String multidataVerifyDesIv = ConfigLoadService.configMap.get("multidata.verify.des.iv");
            String encodeName = SecurityUtil.desEncode(name, multidataVerifyDesKey, multidataVerifyDesIv);
            String encodeIdCard = SecurityUtil.desEncode(cardId, multidataVerifyDesKey, multidataVerifyDesIv);
            String requestId = String.valueOf(System.currentTimeMillis()) + RandomStringUtils.randomNumeric(6);
            String multidataVerifyMd5Key = ConfigLoadService.configMap.get("multidata.verify.md5");
            String signature = SecurityUtil.getMD5((encodeName + encodeIdCard + requestId + multidataVerifyMd5Key).getBytes());
            String multidataVerifyAccount = ConfigLoadService.configMap.get("multidata.verify.account");
            paramsMap.put("account", multidataVerifyAccount);
            paramsMap.put("name", encodeName);
            paramsMap.put("idcard", encodeIdCard);
            paramsMap.put("requestId", requestId);
            paramsMap.put("signature", signature);

            String multidataVerifyUrl = ConfigLoadService.configMap.get("idcardCheckUrl");
//                    commonConfigService.getProperty("multidata.verify.url");
            log.info("众数调用二要素请求:" + multidataVerifyUrl + getParams(paramsMap));
            Map<String, Object> res = HttpClientUtils.execute(multidataVerifyUrl, paramsMap);
            if (res == null || res.get("rs") == null) {
                retMap.put("code", 1);
                retMap.put("msg", "请求第三方数据返回值错误!");
                return retMap;
            }
            String rs = (String) (res.get("rs"));
            String strResponse = SecurityUtil.desDecode(rs, multidataVerifyDesKey, multidataVerifyDesIv, "UTF-8");
            log.info("众数调用二要素返回:" + strResponse);
            retMap.put("code", 0);
            retMap.put("msg", "查询二要素信息成功!");
            JSONObject response = JSONObject.parseObject(strResponse);
            HashMap<String,Object> strResponseMap = Json2MapUtil.json2Map(strResponse);
            HashMap<String,Object> collectMap = new HashMap<>();
            if (strResponseMap.get("resultCode").equals(1001)) {
                collectMap.put("code",0);
            }else {
                collectMap.put("code",1);
            }
            collectMap.put("msg",strResponseMap.get("resultMessage"));
            String resultCode = response.getString("resultCode");
            if (Strings.isNullOrEmpty(resultCode)) {
                retMap.put("code", 1);
                retMap.put("msg", "请求第三方数据返回状态码错误!");
                return retMap;
            }
            retMap.put("data", collectMap);
        } catch (Exception e) {
            retMap.put("code", 2);
            retMap.put("msg", "查询二要素信息异常!");
            log.error("verifyTwoElements 异常 " + e);
        }
        return retMap;
    }

    public HashMap<String, Object> verifyOcr(String image) {

        HashMap<String, Object> resultMap = new HashMap();
        HashMap<String, Object> retMap = new HashMap<>();
        String faceOcrApiKey = ConfigLoadService.configMap.get("faceOcrApiKey");
        String faceOcrApiSecret = ConfigLoadService.configMap.get("faceOcrApiSecret");
        String faceOcrUrl = ConfigLoadService.configMap.get("faceOcrUrl");
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String idCardOcrData = null;
        File imageFile = generateImageFile(image);
        if (imageFile==null) {
            resultMap.put("code", 2);
            resultMap.put("msg", "解析图片时发生异常!");
            log.error("解析图片时发生 异常");
            return resultMap;
        }
        try {
            httpClient = HttpClients.createDefault();
            // 把一个普通参数和文件上传给下面这个地址 是一个servlet
            HttpPost httpPost = new HttpPost(faceOcrUrl);
            // 把文件转换成流对象FileBody
            FileBody bin = new FileBody(imageFile);

            StringBody apiKey = new StringBody(faceOcrApiKey, ContentType.create(
                    "text/plain", Consts.UTF_8));
            StringBody apiSecret = new StringBody(faceOcrApiSecret, ContentType.create(
                    "text/plain", Consts.UTF_8));
            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    // 相当于<input type="file" name="file"/>
                    .addPart("image", bin)
                    // 相当于<input type="text" name="apiKey" value=apiKey>
                    .addPart("api_key", apiKey)
                    .addPart("api_secret", apiSecret)
                    .build();
            httpPost.setEntity(reqEntity);
            // 发起请求 并返回请求的响应
            response = httpClient.execute(httpPost);
            // 获取响应对象
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                // 打印响应长度
                log.info("Response content length: " + resEntity.getContentLength());
                // 打印响应内容
                idCardOcrData = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
                HashMap<String, Object> idCardOcrDatamap = Json2MapUtil.json2Map(idCardOcrData);
                Object errorObj = idCardOcrDatamap.get("error");
                log.error("ocr错误信息error"+errorObj);
                if (errorObj != null) {
                    resultMap.put("code",1);
                    resultMap.put("msg","ocr识别错误!");
                    return resultMap;
                    }
                Integer side = Integer.parseInt(idCardOcrDatamap.get("side").toString());
                if (side.equals(0) || side == 0) {
                    analisisOrcFront(retMap, idCardOcrDatamap);
                }else {
                    if (analisisOcrBack(resultMap, retMap, idCardOcrDatamap)) return resultMap;
                }
                retMap.put("side", side);
                resultMap.put("code",0);
                resultMap.put("msg","图像解析成功!");
                resultMap.put("data",retMap);
            }
            // 销毁
            EntityUtils.consume(resEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 解析ocr背面
     * @param resultMap
     * @param retMap
     * @param idCardOcrDatamap
     * @return
     */
    private boolean analisisOcrBack(HashMap<String, Object> resultMap, HashMap<String, Object> retMap, HashMap<String, Object> idCardOcrDatamap) {
        Map<String, Object> idCardValidDateStartMap = (Map<String, Object>) idCardOcrDatamap.get("valid_date_start");
        String visaStartDate = idCardValidDateStartMap.get("result").toString();
        // 有效期 1999.10.21-2018.10.10
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Map<String, Object> idCardValidDateEndMap = (Map<String, Object>) idCardOcrDatamap.get("valid_date_end");
        String visaEndDate = idCardValidDateEndMap.get("result").toString();
        log.info("OCR身份证背面,有效期startDate=" + visaStartDate );
        log.info("OCR身份证背面,有效期endDate=" + visaEndDate);
        boolean valid = true;
        try {
            format.setLenient(false);
            Date startDate = format.parse(visaStartDate);
            if (visaEndDate.equals("长期")) {
                visaEndDate = "20991231";
            }
            String nowDate = format.format(new Date());
            Long nowTime = format.parse(nowDate).getTime();
            if (startDate.getTime() > nowTime) {
                resultMap.put("code",1);
                resultMap.put("msg","图像解析失败,请保证图片清晰,能够拍摄证件全貌,请重新拍摄");
                return true;
            }
            Date endDate = format.parse(visaEndDate);
            if (startDate.getTime() > endDate.getTime()) {
                valid = false;
                log.error("身份证有效日期visaStartDate=" + visaStartDate + "大于visaEndDate=" + visaEndDate );
            }
        } catch (ParseException e) {
            log.error("身份证有效日期识别有误visaStartDate=" + visaStartDate + ",visaEndDate=" + visaEndDate);
            valid = false;
        }
        if (!valid) {
            resultMap.put("code",1);
            resultMap.put("msg","图像解析失败,请保证图片清晰,能够拍摄证件全貌,请重新拍摄");
            return true;
        }
        String yearStart = visaStartDate.substring(0, 4) + ".";
        String monthStart = visaStartDate.substring(4, 6) + ".";
        String dayStart = visaStartDate.substring(6);
        visaStartDate = yearStart + monthStart + dayStart;

        String yearEnd = visaEndDate.substring(0, 4) + ".";
        String monthEnd = visaEndDate.substring(4, 6) + ".";
        String dayEnd = visaEndDate.substring(6);
        visaEndDate = yearEnd + monthEnd + dayEnd;

        // 签发机关
        Map<String, Object> idCardIssuedByMap = (Map<String, Object>) idCardOcrDatamap.get("issued_by");
        String issuedBy = idCardIssuedByMap.get("result").toString();
        log.info("身份证背面,签发机关:" + issuedBy );
//        // 签发地
//        int index = issuedBy.indexOf("公安局");
//        if (index == -1) {
//            index = issuedBy.indexOf("公安分局");
//        }
//        String issuedAddress = issuedBy.substring(0, index);
        retMap.put("visaStartDate", visaStartDate);
        retMap.put("visaEndDate", visaEndDate);
        // 签发机关
        retMap.put("visaOrgan", issuedBy);
//        // 签发地
//        retMap.put("visaAddress", issuedAddress);
        return false;
    }

    /**
     * 解析ocr反面
     * @param retMap
     * @param idCardOcrDatamap
     */
    private void analisisOrcFront(HashMap<String, Object> retMap, HashMap<String, Object> idCardOcrDatamap) {
        Map<String, Object> idCardNameMap = (Map<String, Object>) idCardOcrDatamap.get("name");
        String name = idCardNameMap.get("result").toString();
        Map<String, Object> idCardNumberMap = (Map<String, Object>) idCardOcrDatamap.get("idcard_number");
        String idCardName = idCardNumberMap.get("result").toString();
        Map<String, Object> idCardBirthYearMap = (Map<String, Object>) idCardOcrDatamap.get("birth_year");
        String yearStr = idCardBirthYearMap.get("result").toString() + "年";
        Map<String, Object> idCardBirthMonthMap = (Map<String, Object>) idCardOcrDatamap.get("birth_month");
        String month = idCardBirthMonthMap.get("result").toString() + "月";
        Map<String, Object> idCardBirthDayMap = (Map<String, Object>) idCardOcrDatamap.get("birth_day");
        String day = idCardBirthDayMap.get("result").toString() + "日";
        //拼接生日
        String birthday = yearStr + month + day;
        // 民族
        Map<String, Object> idCardNationalityMap = (Map<String, Object>) idCardOcrDatamap.get("nationality");
        String race = idCardNationalityMap.get("result").toString();
        // 性别
        Map<String, Object> idCardGenderMap = (Map<String, Object>) idCardOcrDatamap.get("gender");
        String gender = idCardGenderMap.get("result").toString();
        // 详细地址
        Map<String, Object> idCardAddressMap = (Map<String, Object>) idCardOcrDatamap.get("address");
        String address = idCardAddressMap.get("result").toString();
        // 身份证号前两位:省  前四位:市
        String province = idCardName.substring(0, 2);
        String city = idCardName.substring(0, 4);
        retMap.put("realName", name);
        retMap.put("idCardNo", idCardName);
        retMap.put("birthday", birthday);
        retMap.put("race", race);
        retMap.put("detailAddress", address);
        retMap.put("province", province);
        retMap.put("city", city);
        retMap.put("gender", gender);
    }

    /**
     * 人脸识别校验请求参数
     *
     * @param delta     用于校验上传数据的校验字符串,此字符串会由 MegLive SDK 直接返回。
     * @param imageBest 由 MegLive SDK 返回的在活体检测过程中质量最佳的人脸。
     * @param name      姓名
     * @param idCard    身份证号
     * @return
     */
    public HashMap<String,Object> facePlus(String delta, File imageBest, String name, String idCard) {
        HashMap<String, Object> resultMap = new HashMap();
        HashMap<String, Object> retMap = new HashMap<>();
        String faceOcrApiKey = ConfigLoadService.configMap.get("faceOcrApiKey");
        String faceOcrApiSecret = ConfigLoadService.configMap.get("faceOcrApiSecret");
        String faceVerifyUrlKey = ConfigLoadService.configMap.get("faceVerifyUrl");
        String faceVerifyUrl = ConfigLoadService.configMap.get(faceVerifyUrlKey);
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String facePlusData = null;
        try {
            httpClient = HttpClients.createDefault();
            // 把一个普通参数和文件上传给下面这个地址 是一个servlet
            HttpPost httpPost = new HttpPost(faceVerifyUrl);
            // 把文件转换成流对象FileBody
            FileBody bin = new FileBody(imageBest);
            StringBody apiKey = new StringBody(faceOcrApiKey, ContentType.create(
                    "text/plain", Consts.UTF_8));
            StringBody apiSecret = new StringBody(faceOcrApiSecret, ContentType.create(
                    "text/plain", Consts.UTF_8));
            StringBody comparisonTypeContent = new StringBody("1", ContentType.create(
                    "text/plain", Consts.UTF_8));
            StringBody faceImageType = new StringBody("meglive", ContentType.create(
                    "text/plain", Consts.UTF_8));
            StringBody nameContent = new StringBody(name, ContentType.create(
                    "text/plain", Consts.UTF_8));
            StringBody idCardContent = new StringBody(idCard, ContentType.create(
                    "text/plain", Consts.UTF_8));
            StringBody deltaContent = new StringBody(delta, ContentType.create(
                    "text/plain", Consts.UTF_8));

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    // 相当于<input type="file" name="file"/>
                    .addPart("image_best", bin)
                    // 相当于<input type="text" name="apiKey" value=apiKey>
                    .addPart("api_key", apiKey)
                    .addPart("comparison_type",comparisonTypeContent)
                    .addPart("api_secret", apiSecret)
                    .addPart("face_image_type",faceImageType)
                    .addPart("idcard_name", nameContent)
                    .addPart("idcard_number",idCardContent)
                    .addPart("delta",deltaContent)
                    .build();
            httpPost.setEntity(reqEntity);
            // 发起请求 并返回请求的响应
            response = httpClient.execute(httpPost);
            // 获取响应对象
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                // 打印响应内容
                facePlusData = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
                HashMap<String, Object> idCardOcrDatamap = Json2MapUtil.json2Map(facePlusData);
                Object errorObj = idCardOcrDatamap.get("error_message");
                if (errorObj != null) {
                    retMap.put("code",1);
                    retMap.put("msg","比对不一致!");
                    resultMap.put("code",1);
                    resultMap.put("msg","face++识别错误!");
                    resultMap.put("data",retMap);
                    return resultMap;
                }
                retMap.put("code",0);
                retMap.put("msg","比对一致!");
                resultMap.put("code",0);
                resultMap.put("msg","face++识别成功!");
                resultMap.put("data",retMap);
            }
            // 销毁
            EntityUtils.consume(resEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * base64转图片file
     *
     * @param imgStr
     * @return
     */
    public File generateImageFile(String imgStr) {
        // 图像数据为空
        if (imgStr == null) {
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                // 调整异常数据
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            String path = this.getClass().getClassLoader().getResource(File.separator).getPath();
            String fileName = path + IdGenerator.getInstance().generateId() + ".JPEG";
            File newFile = new File(fileName);
            FileOutputStream fos = new FileOutputStream(newFile);
            fos.write(bytes);
            fos.close();
            return newFile;
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {

    }
}

猜你喜欢

转载自blog.csdn.net/u011277745/article/details/88872610