OCR技术,开源免费的技术产品之前小编已经写过,想看请点击 https://www.cnblogs.com/zhizhixiaoxia/p/12015657.html
没事研究了下阿里云收费的OCR技术产品。
以身份证识别为例,代码调用接口实现:(idea编写的Java,maven项目)
1、所需依赖:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version></dependency><dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.15</version></dependency><dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version></dependency>
依赖版本可自行去maven仓库选择下载。
2、需要创建两个类,一个是目标类,一个是http工具类。
目标类:
public class AliyunOcr { public static void main(String[] args){ //idCardIdentify(); } /** * 身份证识别 * */ private static void idCardIdentify() { // 接口访问路径 String host = "http://dm-51.data.aliyun.com"; // 接口请求方式风格 String path = "/rest/160601/ocr/ocr_idcard.json"; // 产品编码 String appcode = "开通服务获取"; // 图片路径 String imgFile = "E://com//dream//begin//image//jpg//idCard//1_3.jpg"; // 如果文档的输入中含有inputs字段,设置为True, 否则设置为False Boolean is_old_format = false; // 请根据线上文档修改configure字段 JSONObject configObj = new JSONObject(); // 身份证正反面参数 front正面,back反面 configObj.put("side", "back"); String config_str = configObj.toString(); // 请求方式 String method = "POST"; Map<String, String> headers = new HashMap<String, String>(); // 最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105 headers.put("Authorization", "APPCODE " + appcode); // url后面的请求参数 Map<String, String> querys = new HashMap<String, String>(); // 对图像进行base64编码 InputStream inputStream = null; byte[] data = null; try { inputStream = new FileInputStream(imgFile); data = new byte[inputStream.available()]; inputStream.read(data); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } // 编码加密 BASE64Encoder encoder = new BASE64Encoder(); String imgBase64 = encoder.encode(data); // 拼装请求body的json字符串 JSONObject requestObj = new JSONObject(); try { // 判断文档输入中是否含有inputs字段 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 { // 发送请求,识别图片 HttpResponse response = AliyunHttpUtils.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(); } } /** * 获取参数的json对象 **/ private 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; } }
http工具类::
public class AliyunHttpUtils { /** * Post String * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (StringUtils.isNotBlank(body)) { request.setEntity(new StringEntity(body, "utf-8")); } return httpClient.execute(request); } private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException { StringBuilder sbUrl = new StringBuilder(); sbUrl.append(host); if (!StringUtils.isBlank(path)) { sbUrl.append(path); } if (null != querys) { StringBuilder sbQuery = new StringBuilder(); for (Map.Entry<String, String> query : querys.entrySet()) { if (0 < sbQuery.length()) { sbQuery.append("&"); } if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) { sbQuery.append(query.getValue()); } if (!StringUtils.isBlank(query.getKey())) { sbQuery.append(query.getKey()); if (!StringUtils.isBlank(query.getValue())) { sbQuery.append("="); sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8")); } } } if (0 < sbQuery.length()) { sbUrl.append("?").append(sbQuery); } } return sbUrl.toString(); } private static HttpClient wrapClient(String host) { HttpClient httpClient = new DefaultHttpClient(); if (host.startsWith("https://")) { sslClient(httpClient); } return httpClient; } private static void sslClient(HttpClient httpClient) { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] xcs, String str) { } public void checkServerTrusted(X509Certificate[] xcs, String str) { } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = httpClient.getConnectionManager(); SchemeRegistry registry = ccm.getSchemeRegistry(); registry.register(new Scheme("https", 443, ssf)); } catch (KeyManagementException ex) { throw new RuntimeException(ex); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } }}
工具类我删除了一些没用到的方法,如有想看完整的请去下载 https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java。
总的来说,阿里云接口的使用,还是很简单的。希望对大伙们能有所帮助。
本人学疏才浅,如有差错,望请指正。
原文地址:https://www.cnblogs.com/zhizhixiaoxia/p/12017317.html
时间: 2024-10-10 22:21:56