java----百度识别身份证识别api使用方法

    xiaoxiao2022-07-02  108

    前言 百度识别api是一个非常实用的工具,他可以非常有效的进行身份信息读取,我们可以通过他来获取到身份证上的所有信息,百度识别不管只具有身份证识别,还有很多证件的识别api。 接下来我们说具体实现流程:首先要引用SDK包,然后获取百度地图提供的accessToken码,然后存入图片路径进行数据返回。 1.引入百度地图SDK包 (1)在http://ai.baidu.com/sdk下载SDK (2)将下载的aip-java-sdk-version.zip解压后,复制到工程文件夹中。 (3)在Eclipse右键“工程 -> Properties -> Java Build Path -> Add JARs”。 (4)添加SDK工具包aip-java-sdk-version.jar和第三方依赖工具包json-20160810.jar log4j-1.2.17.jar。 2.获取accessToken package com.telematics.wx.util;

    import org.json.JSONObject;

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

    /**

    获取token类 / public class AuthService { public static void main(String[] args) { String str= getAuth(); System.out.println(str); } /*

    获取权限token@return 返回示例:{“access_token”: “24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567”,“expires_in”: 2592000} */ public static String getAuth() { // 官网获取的 API Key 更新为你注册的 String clientId = "; // 官网获取的 Secret Key 更新为你注册的 String clientSecret = “”; return getAuth(clientId, clientSecret); }

    /**

    获取API访问token该token有一定的有效期,需要自行管理,当失效时需重新获取.@param ak - 百度云官网获取的 API Key@param sk - 百度云官网获取的 Securet Key@return assess_token 示例:“24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567” / public static String getAuth(String ak, String sk) { // 获取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(“GET”); connection.connect(); // 获取所有响应头字段 Map<String, List> 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.进行识别 @RequestMapping(“test”) @ResponseBody public String test(HttpServletRequest request,HttpServletResponse response, ModelMap model,HttpSession session){ System.out.println(“进入身份识别”); // 身份证识别url String idcardIdentificate = “https://aip.baidubce.com/rest/2.0/ocr/v1/idcard”; // 本地图片路径 String path=session.getServletContext().getRealPath("/upload"); System.out.println(“根目录路径”+path); String filePath = path+"\"+“shenfenzheng.jpg”; System.out.println(“图片路径”+filePath); try { byte[] imgData = FileUtil.readFileByBytes(filePath);//使用工具类进行转码 String imgStr = Base64Util.encode(imgData);//百度地图的所有图片均需要base64编码、去掉编码头后再进行urlencode。//import com.baidu.aip.util.Base64Util; // 识别身份证正面id_card_side=front;识别身份证背面id_card_side=back; String params = “id_card_side=front&” + URLEncoder.encode(“image”, “UTF-8”) + “=” + URLEncoder.encode(imgStr, “UTF-8”); String token=AuthService.getAuth();//调用上面的accessToken码代码 String accessToken = token; String result = HttpUtil.post(idcardIdentificate, accessToken, params); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } return “0”; } 4.工具类 package com.goocom.util;

    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(); }

    } } } 到此结束,第一次写博客有些不太熟练希望大家谅解,有什么要求和评论希望大家一起学习。

    最新回复(0)