通过阿里云API 身份证图片或拍身份证 读取身份证正反面信息

参看文:阿里的资料
https://market.aliyun.com/products/57124001/cmapi010401.html?spm=5176.8243888.554823.2.wXf26h#sku=yuncode440100000

执行 AliOcrIdcard.java就可以了!


package com.zct.yfq.client.fddsignature.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
* A阿里云-数据服务_5_1_身份证识别
* @author 张绪定
*
*/
public class AliOcrIdcard {

public static void main(String[] args) {
// TODO Auto-generated method stub
AliOcrIdcard aliOcrIdcard=new AliOcrIdcard();
System.out.println("===================身份证正面信息===================");
aliOcrIdcard.getAliOcrIdcard("d://yhxface2.jpg", "face");
System.out.println("===================身份证反面信息===================");
aliOcrIdcard.getAliOcrIdcard("d://yhxback2.jpg", "back");
}

/**
* 获取 A阿里云-数据服务_5_1_身份证识别,得到身份证基本信息
* @return
*/
public void getAliOcrIdcard(String imgFile,String configStr){

String host = "https://dm-51.data.aliyun.com";
String path = "/rest/160601/ocr/ocr_idcard.json";
String method = "POST";
Map headers = new HashMap();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE ca5b682163b9440899a6c2b425a4e26b");
Map querys = new HashMap();

String body=getJosnStrRequestBody(getStrImgBase64(imgFile),configStr);

try {
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, body);
String result=EntityUtils.toString(response.getEntity());
JSONObject resultObj = new JSONObject(result);
JSONArray outputArray = resultObj.getJSONArray("outputs");
String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue"); // 取出结果json字符串
JSONObject out = new JSONObject(output);
if (out.getBoolean("success")) {

if(!configStr.isEmpty()&&configStr.equals("face")){
String addr = out.getString("address"); // 获取地址
String configstr = out.getString("config_str"); // 获取身份证正反面face/side
String name = out.getString("name"); // 获取名字
String num = out.getString("num"); // 获取身份证号
String sex = out.getString("sex"); // 获取性别
String birth = out.getString("birth"); // 获取身份证号
String nationality = out.getString("nationality"); // 获取民族
boolean success = out.getBoolean("success"); // 获取识别结果
System.out.printf("addr : %s \n configstr : %s \n name : %s \n num : %s \n sex : %s\n birth : %s\n nationality : %s\n",
addr, configstr, name,num, sex, birth,nationality);
}

if(!configStr.isEmpty()&&configStr.equals("back")){
String configstr = out.getString("config_str"); // 获取身份证正反面face/side
String startdate = out.getString("start_date"); //获取有效期起始时间
String enddate = out.getString("end_date"); // 获取有效期结束时间
String issue = out.getString("issue"); // 获取签发机关
boolean success = out.getBoolean("success"); // 获取识别结果
System.out.printf(" configstr : %s \n startdate : %s\n enddate : %s\n issue : %s\n ", configstr, startdate, enddate,issue);
}

} else {
System.out.println("predict error");
}
} catch (Exception e) {
e.printStackTrace();
}


}

/**
* 获取身份证图片Base64流
* String imgFile explame "d://idcard_example.jpg";
* @return
*/
public static String getStrImgBase64(String imgFile){
// 对图像进行base64编码
String strImgBase64 = "";
try {
File file = new File(imgFile);
byte[] content = new byte[(int) file.length()];
FileInputStream finputstream = new FileInputStream(file);
finputstream.read(content);
finputstream.close();
strImgBase64 = new String(Base64.encodeBase64(content));
} catch (IOException e) {
e.printStackTrace();
}
return strImgBase64;
}

/**
* 获取"身份证识别"请求报文Body(Josn格式的String串)
* strImgBase64:
* configStr:示上传图片是身份证正面/反面图像, "face" 表示正面,"back"表示反面
*/
public static String getJosnStrRequestBody(String strImgBase64,String configStr){
// 拼装请求body的json字符串
JSONObject requestObj = new JSONObject();
try {
JSONObject configObj = new JSONObject();
JSONObject obj = new JSONObject();
JSONArray inputArray = new JSONArray();
//表示上传图片是身份证正面/反面图像, “face” 表示正面,”back”表示反面
configObj.put("side", configStr);
obj.put("image", getParam(50, strImgBase64));
obj.put("configure", getParam(50, configObj.toString()));
inputArray.put(obj);
requestObj.put("inputs", inputArray);;
} catch (JSONException e) {
e.printStackTrace();
}
String requestBody = requestObj.toString();
return requestBody;
}

/**
* 获取参数的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;
}


}







package com.zct.yfq.client.fddsignature.action;

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;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.StringUtils;
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;

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 headers,
Map querys)
throws Exception {
HttpClient httpClient = wrapClient(host);

HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry 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 headers,
Map querys,
Map bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);

HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}

if (bodys != null) {
List nameValuePairList = new ArrayList();

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 headers,
Map querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);

HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry 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 headers,
Map querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);

HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry 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 headers,
Map querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);

HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry 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 headers,
Map querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);

HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry 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 headers,
Map querys)
throws Exception {
HttpClient httpClient = wrapClient(host);

HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}

return httpClient.execute(request);
}

private static String buildUrl(String host, String path, Map 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 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);
}
}
}

你可能感兴趣的:(调用外部API)