テンセントaiプラットフォームをカプセル化して身分証明書を識別するのは静的な方法です

17739 ワード

ブログ参照https://blog.csdn.net/kanglovejava/article/details/80271137
TencentOCRUtilツールクラス
	public class TencentOCRUtil {
    private static Logger log = LoggerFactory.getLogger(TencentOCRUtil.class);
    private static int appId = "your appId";
    private static String appkey = "your appkey";
    
     //  ( )
    public static long getTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

     //  
    public static String getNonceStr() {
        return UUID.randomUUID().toString().replace("-", "").toLowerCase();
    }

   //  
    public static String getReqSign(Map < String, String > param, String appkey) {
        StringBuffer appendStr = new StringBuffer();
        for (String key : param.keySet()) {
            if (!StringUtils.isEmpty(param.get(key))) {
                appendStr.append(key).append("=").append(param.get(key)).append("&");
            }
        }
        appendStr.append("app_key=").append(appkey);
        return getMD5Str(appendStr.toString()).toUpperCase();
    }

    // md5 
    public static String getMD5Str(String str) {
        MessageDigest messageDigest = null;

        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e) {
        }

        byte[] byteArray = messageDigest.digest();

        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }

        return md5StrBuff.toString();
    }

     //  base64 
    public static String getImageStr(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        //  
        // System.out.println("--------------- java.util:"+new String(Base64.getEncoder().encode(data)));
        // BASE64Encoder encoder = new BASE64Encoder();
        // System.out.println("*************** sun.misc:"+encoder.encode(data));

        return new String(Base64.getEncoder().encode(data));
        // BASE64Encoder encoder = new BASE64Encoder();
        // return encoder.encode(data);
    }

    //  
    public static String idNoArith(File file, Integer cardType) {
        try {
            Map < String, String > param = new TreeMap <>();
            param.put("app_id", URLEncoder.encode(String.valueOf(appId), "UTF-8"));
            param.put("image", URLEncoder.encode(getImageStr(file.getAbsolutePath()).replace("\r
", ""), "UTF-8")); param.put("card_type", URLEncoder.encode(cardType + "", "UTF-8")); param.put("time_stamp", URLEncoder.encode(String.valueOf(getTimeStamp()), "UTF-8")); param.put("nonce_str", URLEncoder.encode(getNonceStr(), "UTF-8")); appkey = URLEncoder.encode(appkey, "UTF-8"); String sign = getReqSign(param, appkey); param.put("sign", sign); String result = httpsPost("https://api.ai.qq.com/fcgi-bin/ocr/ocr_idcardocr", param); int ret = Integer.valueOf(JSONObject.fromObject(result).get("ret").toString()); if (ret == 0) { return result; } else { log.error("************** {} , :{}", cardType == 0 ? " " : " ", JSONObject.fromObject(result) .get("msg").toString()); return ""; } } catch (Exception e) { e.printStackTrace(); } return ""; } // post private static String httpsPost(String url, Map param) { URL u = null; HttpURLConnection con = null; // StringBuffer sb = new StringBuffer(); if (param != null) { for (Entry < String, String > e : param.entrySet()) { sb.append(e.getKey()); sb.append("="); sb.append(e.getValue()); sb.append("&"); } sb.substring(0, sb.length() - 1); } // try { u = new URL(url); con = (HttpURLConnection) u.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); // con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); osw.write(sb.toString()); osw.flush(); osw.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.disconnect(); } } StringBuffer buffer = new StringBuffer(); try { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String temp; while ((temp = br.readLine()) != null) { buffer.append(temp); buffer.append("
"); } } catch (Exception e) { e.printStackTrace(); } return buffer.toString(); } // public static IDCardInfo getIDCardInfo(String result, int cardType) { IDCardInfo ocrInfo = new IDCardInfo(); if (cardType == 0) { // String data = JSONObject.fromObject(result).get("data").toString(); JSONObject dataObject = JSONObject.fromObject(data); ocrInfo.setName(dataObject.get("name").toString()); ocrInfo.setSex(dataObject.get("sex").toString()); ocrInfo.setNation(dataObject.get("nation").toString()); ocrInfo.setBirth(dataObject.get("birth").toString()); ocrInfo.setAddress(dataObject.get("address").toString()); ocrInfo.setId(dataObject.get("id").toString()); } else if (cardType == 1) { // String data = JSONObject.fromObject(result).get("data").toString(); JSONObject dataObject = JSONObject.fromObject(data); ocrInfo.setAuthority(dataObject.get("authority").toString()); ocrInfo.setValidDate(dataObject.get("valid_date").toString()); } return ocrInfo; } }

IDCardInfo身分証明書情報パッケージクラス

public class IDCardInfo {
    private String name;

    private String sex;

    private String nation;

    private String birth;

    private String address;

    private String id;

    private String authority;

    private String validDate;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getNation() {
        return nation;
    }

    public void setNation(String nation) {
        this.nation = nation;
    }

    public String getBirth() {
        return birth;
    }

    public void setBirth(String birth) {
        this.birth = birth;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getAuthority() {
        return authority;
    }

    public void setAuthority(String authority) {
        this.authority = authority;
    }

    public String getValidDate() {
        return validDate;
    }

    public void setValidDate(String validDate) {
        this.validDate = validDate;
    }

    @Override
    public String toString() {
        return "IDCardInfo{" + "name='" + name + '\'' + ", sex='" + sex + '\'' + ", nation='" + nation + '\''
                + ", birth='" + birth + '\'' + ", address='" + address + '\'' + ", id='" + id + '\'' + ", authority='"
                + authority + '\'' + ", validDate='" + validDate + '\'' + '}';
    }
}