实现百度ocr识别认证【文字,证件等识别】

认证核心思路:

1.将用户的apikey和密钥换取百度的签证token

2.将识别的图片携带token到百度系统识别数据返回出来

3.获取到token,根据业务识别,识别不同类型的证件只是请求百度识别的地址接口不同

查看密钥和apikey

 

更换自己的apikey,和密钥,即可执行

public class OrcService {
    //1.设置参数密钥
    public static String getAuth(){
        String clientId="老哥你自己的APIKEY";
        String clientSecret="老哥你自己的密钥";
        return getAuth(clientId,clientSecret);
    }

    /**
     * 2.与百度进行校验身份
     * @param ak
     * @param sk
     * @return token
     */
    public static String getAuth(String ak,String sk){
        //2.获取token请求地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败!");
            e.printStackTrace(System.err);
        }
        return null;
    }

    /**
     * 3.发送orc认证请求
     * 读取图片的文字
     * @param httpUrl  百度云的文字识别接口
     * @param httpArg  身份证的正反面参数
     * @return
     */
    public static String  orcRequest(String httpUrl, String httpArg){
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        try {
            //用java JDK自带的URL去请求
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            //设置该请求的消息头
            //设置HTTP方法:POST
            connection.setRequestMethod("POST");
            //设置其Header的Content-Type参数为application/x-www-form-urlencoded
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            // 填入 Apikey到 HTTP header
            connection.setRequestProperty("apikey", "KNYXGnWPmTQlxgUGqQ8G7iPM");
            //将第二步获取到的token填入到HTTP header
            connection.setRequestProperty("access_token", OrcService.getAuth());
            connection.setDoOutput(true);
            connection.getOutputStream().write(httpArg.getBytes("UTF-8"));
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *4.身份证参数转换 ,将json数据转换为map
     * @param jsonResult
     * @return
     */
    public static HashMap<String, String> getHashMapByJson(String jsonResult) {
        HashMap map = new HashMap<String, String>();
        try {
            JSONObject jsonObject = new JSONObject(jsonResult);
            JSONObject words_result = jsonObject.getJSONObject("words_result");
            Iterator<String> it = words_result.keys();
            while (it.hasNext()) {
                String key = it.next();
                JSONObject result = words_result.getJSONObject(key);
                String value = result.getString("words");
                switch (key) {
                    case "姓名":
                        map.put("姓名", value);
                        break;
                    case "民族":
                        map.put("民族", value);
                        break;
                    case "住址":
                        map.put("住址", value);
                        break;
                    case "公民身份号码":
                        map.put("公民身份号码", value);
                        break;
                    case "出生":
                        map.put("出生日期", value);
                        break;
                    case "性别":
                        map.put("性别", value);
                        break;
                    case "失效日期":
                        map.put("失效日期", value);
                        break;
                    case "签发日期":
                        map.put("签发日期", value);
                        break;
                    case "签发机关":
                        map.put("签发机关", value);
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     *  5.转换为base64
     * @param in
     * @throws Exception
     */
    public static String  Base64String(InputStream in) throws Exception {
        //存放输入字节数组
        byte[] outData = null;

        ByteArrayOutputStream arrayOTS = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];

        int len = 0;

        while ((len = in.read(buffer)) != -1) {
            arrayOTS.write(buffer, 0, len);
        }

        outData = arrayOTS.toByteArray();
        //将字节数组数据转换为base64
        return Base64.getEncoder().encodeToString(outData);
    }


    public static void main(String[] args) throws Exception {
        //进行BASE64位编码
        String imageBase = OrcService.Base64String(new ClassPathResource("bbb.jpg").getInputStream());
        imageBase = imageBase.replaceAll("\r\n", "");
        imageBase = imageBase.replaceAll("\\+", "%2B");
        //百度云的文字识别接口,后面参数为获取到的token
        String httpUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + OrcService.getAuth();
        //id_card_side=front 识别正面    id_card_side=back  识别背面
        String httpArg = "detect_direction=true&id_card_side=front&image=" + imageBase;
        String jsonResult = OrcService.orcRequest(httpUrl, httpArg);
        HashMap<String, String> map = getHashMapByJson(jsonResult);
        if( map.get("姓名").equals("")){
            System.out.println("证件不合法");
        }
        System.out.println(jsonResult);
    }
    //身份证识别
    public static Map<String, String> idcard() throws Exception {
        //进行BASE64位编码
        String imageBase = OrcService.Base64String(new ClassPathResource("bbb.jpg").getInputStream());
        imageBase = imageBase.replaceAll("\r\n", "");
        imageBase = imageBase.replaceAll("\\+", "%2B");
        //百度云的文字识别接口,后面参数为获取到的token
        String httpUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + OrcService.getAuth();
        //id_card_side=front 识别正面    id_card_side=back  识别背面
        String httpArg = "detect_direction=true&id_card_side=front&image=" + imageBase;
        String jsonResult = OrcService.orcRequest(httpUrl, httpArg);
        Map<String, String> map = getHashMapByJson(jsonResult);
        if( map.get("姓名").equals("")){
            System.out.println("证件不合法");
        }
        System.out.println(jsonResult);
        return map;
    }
}

 

posted @ 2020-09-16 23:05  萧何~  阅读(959)  评论(0编辑  收藏  举报