Java Baidu Intelligent Cloud (ID Card Recognition)

The first step: to get the access_token key.

parameter

value

access_token

Access_token obtained through API Key and Secret Key, refer to " Access Token Obtaining

AIP:https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials

static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, "&client_id="+API_KEY+"&client_secret="+SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = null;
        try {
            response = HTTP_CLIENT.newCall(request).execute();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //只会调用一次
//        System.out.println(response.body().string());
        try {
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            String accessToken = jsonObject.getString("access_token");
            System.out.println("accessToken="+accessToken);

Step 2: Upload your ID card and verify your ID card

Request parameters:

 // 请求url
                String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
                //图片地址
                String filePath = pats;
                System.out.println("filePath=" + filePath);
//            String filePath = "C://Users/29291/Desktop/12.png";
                //String filePath = "https://gulimall-vues.oss-cn-chengdu.aliyuncs.com/11.jpg";
                byte[] imgData = FileUtil.readFileByBytes(filePath);
                String imgStr = Base64Util.encode(imgData);
                String imgParam = URLEncoder.encode(imgStr, "UTF-8");
                //拼接参数
                String param = "id_card_side=" + "back" + "&image=" + imgParam + "&detect_risk=" + "true";
                // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
                String accessTokens = accessToken;
                String result = HttpUtils.post(url, accessTokens, param);
                System.out.println("result=" + result);
                JSONObject jsonObjects = JSONObject.parseObject(result);
                String riskType = jsonObjects.getString("risk_type");
                System.out.println("riskType=" + riskType);
                if (!riskType.equals("normal")) {
                    new File(pats).delete();
                    System.out.println("请上传有效身份证");
                    return R.error("请上传有效身份证");
                }
                //身份证信息
                String name = jsonObjects.getJSONObject("words_result").getJSONObject("姓名").getString("words");
                System.out.println("name=" + name);
                //判断信息是否一致
                if (!name.equals(fullName)) {
                    new File(pats).delete();
                    return R.error("信息错误,请重新认证");
                }
                String nation = jsonObjects.getJSONObject("words_result").getJSONObject("民族").getString("words");
                String address = jsonObjects.getJSONObject("words_result").getJSONObject("住址").getString("words");
                String card = jsonObjects.getJSONObject("words_result").getJSONObject("公民身份号码").getString("words");
                String birthday = jsonObjects.getJSONObject("words_result").getJSONObject("出生").getString("words");
                String sex = jsonObjects.getJSONObject("words_result").getJSONObject("性别").getString("words");
                new File(pats).delete();
                Courier courier1=new Courier();
                courier1.setIdentityStatus("1");
                courier1.setCourierId(courierId);
                courierService.updateCourier(courier1);

parameter

Is it required?

type

Optional value range

illustrate

image

Choose one from the url

string

-

Image data is base64 encoded and then urlencoded. The size after base64 encoding and urlencode is required to be no more than 4M, with the shortest side at least 15px and the longest side up to 4096px. jpg/jpeg/png/bmp formats are supported.

url

Choose one from image

string

-

The complete URL of the image. The length of the URL does not exceed 1024 bytes. The base64-encoded size of the image corresponding to the URL does not exceed 4M. The shortest side is at least 15px and the longest side is up to 4096px. The jpg/jpeg/png/bmp format is supported when the image field exists. The url field is invalid.
Please turn off URL anti-hotlinking.

id_card_side

yes

string

front/back

-front: The side of the ID card with the photo
-back: The side of the ID card with the national emblem.
Automatically detect the front and back of the ID card. If the direction specified by the parameter is opposite to the picture, normal recognition is supported, and the returned parameter image_status field is "reversed_side"

detect_risk

no

string

true/false

Whether to enable the detection function of ID card risk types (ID card copy, temporary ID card, ID card copy, modified ID card), it is not enabled by default, that is: false.
- true: turned on, please check the return parameter risk_type;
- false: not turned on

detect_quality

no

string

true/false

Whether to turn on the ID card quality type (incomplete border/corners, blocked avatar or key fields/mosaic) detection function, it is not turned on by default, that is: false.
- true: enabled, please check the return parameter card_quality;
- false: not enabled

detect_photo

no

string

true/false

Whether to detect avatar content, not detected by default. Optional value: true - detect the avatar and return the base64 encoding and location information of the avatar

detect_card

no

string

true/false

Whether to detect the ID card for cropping, not detected by default. Optional value: true - detect the ID card and return the base64 encoding and location information of the ID card

 // 请求url
                String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
                //图片地址
                String filePath = pats;
                System.out.println("filePath=" + filePath);
//            String filePath = "C://Users/29291/Desktop/12.png";
                //String filePath = "https://gulimall-vues.oss-cn-chengdu.aliyuncs.com/11.jpg";
                byte[] imgData = FileUtil.readFileByBytes(filePath);
                String imgStr = Base64Util.encode(imgData);
                String imgParam = URLEncoder.encode(imgStr, "UTF-8");
                //拼接参数
                String param = "id_card_side=" + "back" + "&image=" + imgParam + "&detect_risk=" + "true";
                // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
                String accessTokens = accessToken;
                String result = HttpUtils.post(url, accessTokens, param);
                System.out.println("result=" + result);
                JSONObject jsonObjects = JSONObject.parseObject(result);
                String riskType = jsonObjects.getString("risk_type");
                System.out.println("riskType=" + riskType);
                if (!riskType.equals("normal")) {
                    new File(pats).delete();
                    System.out.println("请上传有效身份证");
                    return R.error("请上传有效身份证");
                }
                //身份证信息
                String name = jsonObjects.getJSONObject("words_result").getJSONObject("姓名").getString("words");
                System.out.println("name=" + name);
                //判断信息是否一致
                if (!name.equals(fullName)) {
                    new File(pats).delete();
                    return R.error("信息错误,请重新认证");
                }
                String nation = jsonObjects.getJSONObject("words_result").getJSONObject("民族").getString("words");
                String address = jsonObjects.getJSONObject("words_result").getJSONObject("住址").getString("words");
                String card = jsonObjects.getJSONObject("words_result").getJSONObject("公民身份号码").getString("words");
                String birthday = jsonObjects.getJSONObject("words_result").getJSONObject("出生").getString("words");
                String sex = jsonObjects.getJSONObject("words_result").getJSONObject("性别").getString("words");
                new File(pats).delete();
                Courier courier1=new Courier();
                courier1.setIdentityStatus("1");
                courier1.setCourierId(courierId);
                courierService.updateCourier(courier1);
package com.td.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * http 工具类
 */
public class HttpUtils {

    public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        return HttpUtils.post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return HttpUtils.post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return HttpUtils.postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
            System.err.println(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        System.err.println("result:" + result);
        return result;
    }
}
package com.td.utils;

import java.io.*;

/**
 * 文件读取工具类
 */
public class FileUtil {

    /**
     * 读取文件内容,作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流
        FileInputStream fis = new FileInputStream(filePath);
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];
        // 用于保存实际读取的字节数
        int hasRead = 0;
        while ( (hasRead = fis.read(bbuf)) > 0 ) {
            sb.append(new String(bbuf, 0, hasRead));
        }
        fis.close();
        return sb.toString();
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }
}
package com.td.utils;

/**
 * Base64 工具类
 */
public class Base64Util {
    private static final char last2byte = (char) Integer.parseInt("00000011", 2);
    private static final char last4byte = (char) Integer.parseInt("00001111", 2);
    private static final char last6byte = (char) Integer.parseInt("00111111", 2);
    private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
    private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
    private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
    private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};

    public Base64Util() {
    }

    public static String encode(byte[] from) {
        StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
        int num = 0;
        char currentByte = 0;

        int i;
        for (i = 0; i < from.length; ++i) {
            for (num %= 8; num < 8; num += 6) {
                switch (num) {
                    case 0:
                        currentByte = (char) (from[i] & lead6byte);
                        currentByte = (char) (currentByte >>> 2);
                    case 1:
                    case 3:
                    case 5:
                    default:
                        break;
                    case 2:
                        currentByte = (char) (from[i] & last6byte);
                        break;
                    case 4:
                        currentByte = (char) (from[i] & last4byte);
                        currentByte = (char) (currentByte << 2);
                        if (i + 1 < from.length) {
                            currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
                        }
                        break;
                    case 6:
                        currentByte = (char) (from[i] & last2byte);
                        currentByte = (char) (currentByte << 4);
                        if (i + 1 < from.length) {
                            currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
                        }
                }

                to.append(encodeTable[currentByte]);
            }
        }

        if (to.length() % 4 != 0) {
            for (i = 4 - to.length() % 4; i > 0; --i) {
                to.append("=");
            }
        }

        return to.toString();
    }
}

Acho que você gosta

Origin blog.csdn.net/m0_55699184/article/details/130890200
Recomendado
Clasificación