封装腾讯ai平台识别身份证为静态方法

参考博客 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\n", ""), "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("\n");
            }
        }
        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 + '\'' + '}';
    }
}

你可能感兴趣的:(封装腾讯ai平台识别身份证为静态方法)