阿里雲國際護照識別
阿新 • • 發佈:2022-05-28
阿里雲國際護照識別
工具類
import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HttpUtils { /** * get * * @param host * @param path * @param method * @param headers * @param querys * @return * @throws Exception */ public static HttpResponse doGet(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception { HttpClient httpClient = wrapClient(host); HttpGet request = new HttpGet(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } return httpClient.execute(request); } /** * post form * * @param host * @param path * @param method * @param headers * @param querys * @param bodys * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys) 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 (bodys != null) { List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); for (String key : bodys.keySet()) { nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key))); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8"); formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8"); request.setEntity(formEntity); } return httpClient.execute(request); } /** * 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); } /** * Post stream * * @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, byte[] 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 (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); } /** * Put String * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(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); } /** * Put stream * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); } /** * Delete * * @param host * @param path * @param method * @param headers * @param querys * @return * @throws Exception */ public static HttpResponse doDelete(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception { HttpClient httpClient = wrapClient(host); HttpDelete request = new HttpDelete(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } 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() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] xcs, String str) { } @Override 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); } } }
一個類搞定
package com.ruoyi.common.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; 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; /** * 國際護照識別 * * 呼叫地址:http(s)://ocrhz.market.alicloudapi.com/rest/160601/ocr/ocr_passport.json * 請求方式:POST * * 返回型別:JSON * <p> * 圖片大小建議不要超過 1.5M * <p> * 正常返回示例 * <p> * <p> * { * "authority": "公安部出入境管理局*", #簽發機關 * "birth_date": "19861030", #生日 * "birth_day": "861030", #生日(即將棄用) * "birth_place": "廣西", #出生地 * "birth_place_raw":"廣西/GUANGXI", #出生地帶拼音(新增介面) * "country": "CHN", #國籍 * "expiry_date": "20230501", #到期日期 * "expiry_day": "230501", #到期日期(即將棄用) * "issue_date": "20130502", #發證日期 * "issue_place": "廣西", #發證地址 * "issue_place_raw":"廣西/GUANGXI", #發證地址帶拼音(新增介面) * "line0": "P0CHNWANG<<JING<<<<<<<<<<<<<<<<<<<<<<<<<<", * "line1": "E203545580CHN8610304M2305019MNPELOLIOKLPA938", * "name": "WANG.JING", #姓名英文 * "name_cn": "汪婧", #姓名中文 * "name_cn_raw": "汪婧WANGJING", #姓名中文包含拼音(新增介面) * "passport_no": "E20354xxxx", #護照號碼 * "person_id": "MNPELOLIOKLPA9", #持照人身份ID * "request_id": "20171120113612_813974f02a16b81ab911292d181b0b42", #請求唯一標識,用於錯誤追蹤 * "sex": "M", #性別 * "src_country": "CHN", #國籍 * "success": true, * "type": "P0" #護照型別 * } * * */ public class PassportUtils { /* * 獲取引數的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 Map<String,String> getPassport(){ return new Map<String, String>; } public static void main(String[] args) { //呼叫地址 String host = "https://ocrhz.market.alicloudapi.com"; String path = "/rest/160601/ocr/ocr_passport.json"; //TODO String appcode = "你的appcode"; //圖片路徑 String imgFile = "你的圖片路徑"; Boolean is_old_format = false;//如果文件的輸入中含有inputs欄位,設定為True, 否則設定為False String config_str = ""; //請求方式 String method = "POST"; Map<String, String> headers = new HashMap<String, String>(); Map<String, String> querys = new HashMap<String, String>(); headers.put("Authorization", "APPCODE " + appcode); // 用於存放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(); //對影象進行base64編碼 imgBase64 = new String(encodeBase64(content)); } catch (IOException e) { e.printStackTrace(); return; } // 拼裝請求body的json字串 JSONObject requestObj = new JSONObject(); try { if (is_old_format) { //建立JSON物件 JSONObject obj = new JSONObject(); //儲存圖片到JSON物件 obj.put("image", getParam(50, imgBase64)); if (config_str.length() > 0) { obj.put("configure", getParam(50, config_str)); } //建立JSON陣列物件 JSONArray inputArray = new JSONArray(); //將圖片JSON物件存入JSON陣列 inputArray.add(obj); //將JSON圖片陣列存入請求體 requestObj.put("inputs", inputArray); } else { requestObj.put("image", imgBase64); if (config_str.length() > 0) { requestObj.put("configure", config_str); } } } catch (JSONException e) { e.printStackTrace(); } //請求體JSON轉字串 String bodys = requestObj.toString(); try { //傳送Post請求 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()); //解析JSON JSONObject res_obj = JSON.parseObject(res); if (is_old_format) { //獲取JSON陣列 JSONArray outputArray = res_obj.getJSONArray("outputs"); //獲取JSON陣列中的第0位JSON物件的JSON物件的字串 String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue"); //解析JSON字串 JSONObject out = JSON.parseObject(output); System.out.println(out.toJSONString()); } else { System.out.println(res_obj.toJSONString()); } } catch (Exception e) { e.printStackTrace(); } } }