實現百度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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM