公司要求作身份证识别,一开始在网上搜索java方面有Tesseract-OCR的开源技术识别率可以达到99.99%。但真正接触下来,是说这个技术识别率可以达到99.99%,但需要大量的训练数据,也就是人工智能那一套。搞了半天根本达不到理想要求。那有没有其他办法那,查找了下中国的3大巨头公司阿里,腾讯、百度都有提供身份证识别接口。那就走调用第三方的方法吧。我选择了阿里。
前提:
1、需要申请一个阿里账号,有淘宝号的用淘宝号登录也可以。
2、然后在云市场搜索“印刷文字识别-身份证”。
3、阿里免费提供500次识别。需要购买该产品。
4、产品购买成功后,获取appcode值,这个要放到header中去的。
5、就可调用用了。
需要的jar包:
Maven项目直接配置依赖就可以,非maven项目就需要导入jar包:
Commons-lang-2.4.jar、fastjson-1.2.7.jar、httpclient-4.5.6.jar、httpcode-4.4.10.jar、servlet-api.jar基本这几个就够用了。
官方文档:https://market.aliyun.com/products/57124001/cmapi010401.html?spm=5176.730005.productlist.d_cmapi010401.stMjsY#sku=yuncode440100000
其他的不说调用代码如下:
import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONException;import com.alibaba.fastjson.JSONObject;import com.aliyun.api.gateway.demo.util.HttpUtils;import org.apache.http.HttpResponse;import org.apache.http.util.EntityUtils;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.util.HashMap;import java.util.Map;import static org.apache.commons.codec.binary.Base64.encodeBase64;/** * 使用APPCODE进行云市场ocr服务接口调用 */public class APPCodeDemo { /* * 获取参数的json对象 */ public static JSONObject getParam(int type, String dataValue) { JSONObject obj = new JSONObject(); try { obj.put("dataType", type); obj.put("dataValue", dataValue); } catch (JSONException e) { e.printStackTrace(); } return obj; } public static void main(String[] args){ String host = "http://dm-51.data.aliyun.com"; String path = "/rest/160601/ocr/ocr_idcard.json"; String appcode = "你的APPCODE"; String imgFile = "图片路径"; Boolean is_old_format = false;//如果文档的输入中含有inputs字段,设置为True, 否则设置为False //请根据线上文档修改configure字段 JSONObject configObj = new JSONObject(); configObj.put("side", "face"); String config_str = configObj.toString(); // configObj.put("min_size", 5); // String config_str = ""; String method = "POST"; Mapheaders = new HashMap (); //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105 headers.put("Authorization", "APPCODE " + appcode); Map querys = new HashMap (); // 对图像进行base64编码 String imgBase64 = ""; try { File file = new File(imgFile); byte[] content = new byte[(int) file.length()]; FileInputStream finputstream = new FileInputStream(file); finputstream.read(content); finputstream.close(); imgBase64 = new String(encodeBase64(content)); } catch (IOException e) { e.printStackTrace(); return; } // 拼装请求body的json字符串 JSONObject requestObj = new JSONObject(); try { if(is_old_format) { JSONObject obj = new JSONObject(); obj.put("image", getParam(50, imgBase64)); if(config_str.length() > 0) { obj.put("configure", getParam(50, config_str)); } JSONArray inputArray = new JSONArray(); inputArray.add(obj); requestObj.put("inputs", inputArray); }else{ requestObj.put("image", imgBase64); if(config_str.length() > 0) { requestObj.put("configure", config_str); } } } catch (JSONException e) { e.printStackTrace(); } String bodys = requestObj.toString(); try { /** * 重要提示如下: * HttpUtils请从 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java * 下载 * * 相应的依赖请参照 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml */ HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys); int stat = response.getStatusLine().getStatusCode(); if(stat != 200){ System.out.println("Http code: " + stat); System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message")); System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity())); return; } String res = EntityUtils.toString(response.getEntity()); JSONObject res_obj = JSON.parseObject(res); if(is_old_format) { JSONArray outputArray = res_obj.getJSONArray("outputs"); String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue"); JSONObject out = JSON.parseObject(output); System.out.println(out.toJSONString()); }else{ System.out.println(res_obj.toJSONString()); } } catch (Exception e) { e.printStackTrace(); } }}
工具类HttpUtils:
1 import java.io.UnsupportedEncodingException; 2 import java.net.URLEncoder; 3 import java.security.KeyManagementException; 4 import java.security.NoSuchAlgorithmException; 5 import java.security.cert.X509Certificate; 6 import java.util.ArrayList; 7 import java.util.List; 8 import java.util.Map; 9 10 import javax.net.ssl.SSLContext; 11 import javax.net.ssl.TrustManager; 12 import javax.net.ssl.X509TrustManager; 13 14 import org.apache.commons.lang.StringUtils; 15 import org.apache.http.HttpResponse; 16 import org.apache.http.NameValuePair; 17 import org.apache.http.client.HttpClient; 18 import org.apache.http.client.entity.UrlEncodedFormEntity; 19 import org.apache.http.client.methods.HttpDelete; 20 import org.apache.http.client.methods.HttpGet; 21 import org.apache.http.client.methods.HttpPost; 22 import org.apache.http.client.methods.HttpPut; 23 import org.apache.http.conn.ClientConnectionManager; 24 import org.apache.http.conn.scheme.Scheme; 25 import org.apache.http.conn.scheme.SchemeRegistry; 26 import org.apache.http.conn.ssl.SSLSocketFactory; 27 import org.apache.http.entity.ByteArrayEntity; 28 import org.apache.http.entity.StringEntity; 29 import org.apache.http.impl.client.DefaultHttpClient; 30 import org.apache.http.message.BasicNameValuePair; 31 32 public class HttpUtils { 33 34 /** 35 * get 36 * 37 * @param host 38 * @param path 39 * @param method 40 * @param headers 41 * @param querys 42 * @return 43 * @throws Exception 44 */ 45 public static HttpResponse doGet(String host, String path, String method, 46 Mapheaders, 47 Map querys) 48 throws Exception { 49 HttpClient httpClient = wrapClient(host); 50 51 HttpGet request = new HttpGet(buildUrl(host, path, querys)); 52 for (Map.Entry e : headers.entrySet()) { 53 request.addHeader(e.getKey(), e.getValue()); 54 } 55 56 return httpClient.execute(request); 57 } 58 59 /** 60 * post form 61 * 62 * @param host 63 * @param path 64 * @param method 65 * @param headers 66 * @param querys 67 * @param bodys 68 * @return 69 * @throws Exception 70 */ 71 public static HttpResponse doPost(String host, String path, String method, 72 Map headers, 73 Map querys, 74 Map bodys) 75 throws Exception { 76 HttpClient httpClient = wrapClient(host); 77 78 HttpPost request = new HttpPost(buildUrl(host, path, querys)); 79 for (Map.Entry e : headers.entrySet()) { 80 request.addHeader(e.getKey(), e.getValue()); 81 } 82 83 if (bodys != null) { 84 List nameValuePairList = new ArrayList (); 85 86 for (String key : bodys.keySet()) { 87 nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key))); 88 } 89 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8"); 90 formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8"); 91 request.setEntity(formEntity); 92 } 93 94 return httpClient.execute(request); 95 } 96 97 /** 98 * Post String 99 *100 * @param host101 * @param path102 * @param method103 * @param headers104 * @param querys105 * @param body106 * @return107 * @throws Exception108 */109 public static HttpResponse doPost(String host, String path, String method,110 Map headers,111 Map querys,112 String body)113 throws Exception {114 HttpClient httpClient = wrapClient(host);115 116 HttpPost request = new HttpPost(buildUrl(host, path, querys));117 for (Map.Entry e : headers.entrySet()) {118 request.addHeader(e.getKey(), e.getValue());119 }120 121 if (StringUtils.isNotBlank(body)) {122 request.setEntity(new StringEntity(body, "utf-8"));123 }124 125 return httpClient.execute(request);126 }127 128 /**129 * Post stream130 *131 * @param host132 * @param path133 * @param method134 * @param headers135 * @param querys136 * @param body137 * @return138 * @throws Exception139 */140 public static HttpResponse doPost(String host, String path, String method,141 Map headers,142 Map querys,143 byte[] body)144 throws Exception {145 HttpClient httpClient = wrapClient(host);146 147 HttpPost request = new HttpPost(buildUrl(host, path, querys));148 for (Map.Entry e : headers.entrySet()) {149 request.addHeader(e.getKey(), e.getValue());150 }151 152 if (body != null) {153 request.setEntity(new ByteArrayEntity(body));154 }155 156 return httpClient.execute(request);157 }158 159 /**160 * Put String161 * @param host162 * @param path163 * @param method164 * @param headers165 * @param querys166 * @param body167 * @return168 * @throws Exception169 */170 public static HttpResponse doPut(String host, String path, String method,171 Map headers,172 Map querys,173 String body)174 throws Exception {175 HttpClient httpClient = wrapClient(host);176 177 HttpPut request = new HttpPut(buildUrl(host, path, querys));178 for (Map.Entry e : headers.entrySet()) {179 request.addHeader(e.getKey(), e.getValue());180 }181 182 if (StringUtils.isNotBlank(body)) {183 request.setEntity(new StringEntity(body, "utf-8"));184 }185 186 return httpClient.execute(request);187 }188 189 /**190 * Put stream191 * @param host192 * @param path193 * @param method194 * @param headers195 * @param querys196 * @param body197 * @return198 * @throws Exception199 */200 public static HttpResponse doPut(String host, String path, String method,201 Map headers,202 Map querys,203 byte[] body)204 throws Exception {205 HttpClient httpClient = wrapClient(host);206 207 HttpPut request = new HttpPut(buildUrl(host, path, querys));208 for (Map.Entry e : headers.entrySet()) {209 request.addHeader(e.getKey(), e.getValue());210 }211 212 if (body != null) {213 request.setEntity(new ByteArrayEntity(body));214 }215 216 return httpClient.execute(request);217 }218 219 /**220 * Delete221 *222 * @param host223 * @param path224 * @param method225 * @param headers226 * @param querys227 * @return228 * @throws Exception229 */230 public static HttpResponse doDelete(String host, String path, String method,231 Map headers,232 Map querys)233 throws Exception {234 HttpClient httpClient = wrapClient(host);235 236 HttpDelete request = new HttpDelete(buildUrl(host, path, querys));237 for (Map.Entry e : headers.entrySet()) {238 request.addHeader(e.getKey(), e.getValue());239 }240 241 return httpClient.execute(request);242 }243 244 private static String buildUrl(String host, String path, Map querys) throws UnsupportedEncodingException {245 StringBuilder sbUrl = new StringBuilder();246 sbUrl.append(host);247 if (!StringUtils.isBlank(path)) {248 sbUrl.append(path);249 }250 if (null != querys) {251 StringBuilder sbQuery = new StringBuilder();252 for (Map.Entry query : querys.entrySet()) {253 if (0 < sbQuery.length()) {254 sbQuery.append("&");255 }256 if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {257 sbQuery.append(query.getValue());258 }259 if (!StringUtils.isBlank(query.getKey())) {260 sbQuery.append(query.getKey());261 if (!StringUtils.isBlank(query.getValue())) {262 sbQuery.append("=");263 sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));264 }265 }266 }267 if (0 < sbQuery.length()) {268 sbUrl.append("?").append(sbQuery);269 }270 }271 272 return sbUrl.toString();273 }274 275 private static HttpClient wrapClient(String host) {276 HttpClient httpClient = new DefaultHttpClient();277 if (host.startsWith("https://")) {278 sslClient(httpClient);279 }280 281 return httpClient;282 }283 284 private static void sslClient(HttpClient httpClient) {285 try {286 SSLContext ctx = SSLContext.getInstance("TLS");287 X509TrustManager tm = new X509TrustManager() {288 public X509Certificate[] getAcceptedIssuers() {289 return null;290 }291 public void checkClientTrusted(X509Certificate[] xcs, String str) {292 293 }294 public void checkServerTrusted(X509Certificate[] xcs, String str) {295 296 }297 };298 ctx.init(null, new TrustManager[] { tm }, null);299 SSLSocketFactory ssf = new SSLSocketFactory(ctx);300 ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);301 ClientConnectionManager ccm = httpClient.getConnectionManager();302 SchemeRegistry registry = ccm.getSchemeRegistry();303 registry.register(new Scheme("https", 443, ssf));304 } catch (KeyManagementException ex) {305 throw new RuntimeException(ex);306 } catch (NoSuchAlgorithmException ex) {307 throw new RuntimeException(ex);308 }309 }310 }
识别结果正确率已经达到可用。
{"sex":"男","num":"410527**********","birth":"1990**","request_id":"20180801150222_a325b5b8ea94c5c3ab2b7c98310252ef","nationality":"汉","address":"河南省******","name":"***","config_str":"{\"side\":\"face\"}","success":true,"face_rect":{"center":{"y":488,"x":1412},"angle":-90,"size":{"height":240,"width":208}}}