调用阿里云身份证识别接口(使用appcode方式)

来源:互联网 发布:洁伶卫生巾 销售网络 编辑:程序博客网 时间:2024/04/30 16:37

1,创建maven工程,导入依赖(当然,普通java工程也ok)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>image-orc</groupId><artifactId>lcm.test.aliyun.ORC</artifactId><version>0.0.1-SNAPSHOT</version><repositories><repository><id>nexus</id><name>Team Nexus Repository</name><url>http://maven.aliyun.com/nexus/content/groups/public</url><releases><enabled>true</enabled></releases><snapshots><enabled>false</enabled></snapshots></repository></repositories><dependencies><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.15</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.2.1</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.2.1</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-util</artifactId><version>9.3.7.v20160115</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.5</version><scope>test</scope></dependency><dependency><groupId>com.vdurmont</groupId><artifactId>emoji-Java</artifactId><version>3.1.3</version></dependency></dependencies></project>
2,开发代码(直接去阿里官网复制的案例)

package reco;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;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.JSONObject;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;public class TestAliyunImageOrc {static BASE64Encoder encoder = new sun.misc.BASE64Encoder();static BASE64Decoder decoder = new sun.misc.BASE64Decoder();public static void main(String[] args) throws FileNotFoundException {String host = "https://dm-51.data.aliyun.com";String path = "/rest/160601/ocr/ocr_idcard.json";String method = "POST";String appcode = "你申请的appcode(有得地方也用appkey和secret,我猜想,这两个应该是一样的)";Map<String, String> headers = new HashMap<String, String>();// 最后在header中的格式(中间是英文空格)为Authorization:APPCODE// 83359fd73fe94948385f570e3c139105headers.put("Authorization", "APPCODE " + appcode);String pathImage = "E:/cxf/develop-workspace-new/upadmin/temp/1490800942598.png";String binaryToString = getImageBinaryToString(pathImage);// encoder.encodeToString(pathImage.get);// 根据API的要求,定义相对应的Content-Typeheaders.put("Content-Type", "application/json; charset=UTF-8");Map<String, String> querys = new HashMap<String, String>();String bodys = "{\"inputs\": [{\"image\": {\"dataType\": 50,\"dataValue\": \"" + binaryToString+ "\"},\"configure\": {\"dataType\": 50,\"dataValue\": \"{\\\"side\\\":\\\"face\\\"}\"}}]}";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);JSONObject resultObj = new JSONObject(EntityUtils.toString(response.getEntity()));JSONArray outputArray = resultObj.getJSONArray("outputs");String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue"); // 取出结果json字符串JSONObject out = new JSONObject(output);if (out.getBoolean("success")) {String addr = out.getString("address"); // 获取地址String name = out.getString("name"); // 获取名字String birth = out.getString("birth"); // 获取名字String sex = out.getString("sex"); // 获取性别String nationality = out.getString("nationality"); // 获取性别String num = out.getString("num"); // 获取身份证号System.out.printf(" name : %s \n sex : %s \n birth : %s \n nationality : %s \n num : %s\n address : %s\n", name, sex,birth,nationality, num, addr);} else {System.out.println("predict error");}} catch (Exception e) {e.printStackTrace();}}/** * 获取图片的base64编码数据 * </p> *  * @param imagePath * @return */public static String getImageBinaryToString(String imagePath) {try {File file = new File(imagePath);byte[] content = new byte[(int) file.length()];FileInputStream finputstream = new FileInputStream(file);finputstream.read(content);finputstream.close();return new String(Base64.encodeBase64(content));} catch (IOException e) {e.printStackTrace();return null;}}}
httpUtils忘了

package reco;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<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() {                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);        }    }}


最后别忘了导入 org.json的jar包,当时应没有找到maven坐标,所以直接放进去了,哈哈



1 0
原创粉丝点击