阿里云国际护照识别

阿里云国际护照识别

工具类

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();
}
}
}
posted @   锅巴编程  阅读(187)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示