1.pom.xml
<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>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency>2.HttpUtils.java
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 * * host * path * method * headers * 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); } } }3.IDcard_back.java
public class IDcard_back {
public IDcard_back() {
} //发证机关 private String issue; //起始时间 private String start_date; //截止日期 private String end_date; //验证状态 private boolean success; public String getIssue() { return issue; } public void setIssue(String issue) { this.issue = issue; } public String getStart_date() { return start_date; } public void setStart_date(String start_date) { this.start_date = start_date; } public String getEnd_date() { return end_date; } public void setEnd_date(String end_date) { this.end_date = end_date; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } }4.IDcard_face.java
public class IDcard_face {
public IDcard_face() {
} //身份证号 private String num; //姓名 private String name; //出生日期 private String birth; //民族 private String nationality; //性别 private String sex; //地址 private String address; //验证状态 private boolean success;public String getNum() {
return num; }public void setNum(String num) {
this.num = num; }public String getName() {
return name; }public void setName(String name) {
this.name = name; }public String getBirth() {
return birth; }public void setBirth(String birth) {
this.birth = birth; }public String getNationality() {
return nationality; }public void setNationality(String nationality) {
this.nationality = nationality; }public String getSex() {
return sex; }public void setSex(String sex) {
this.sex = sex; } public String getAddress() { return address; }public void setAddress(String address) {
this.address = address; } public boolean isSuccess() { return success; }public void setSuccess(boolean success) {
this.success = success; } }5.IDcard.java
import java.io.File;
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject;import net.coobird.thumbnailator.Thumbnails;
import sun.misc.BASE64Encoder;public class IDcard {
private static String host = "https://dm-51.data.aliyun.com"; private static String path = "/rest/160601/ocr/ocr_idcard.json"; private static String method = "POST"; private static String appcode = ""; /* * 获取参数的json对象 */ public static JSONObject getParam(int type, JSONObject dataValue) { JSONObject obj = new JSONObject(); try { obj.put("dataType", type); obj.put("dataValue", dataValue); } catch (JSONException e) { e.printStackTrace(); } return obj; }/*
* 获取参数的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 JSONObject getConfigureSide(String side) { JSONObject json_side = new JSONObject(); json_side.put("side",side); return getParam(50, JSON.toJSONString(json_side)); } public static JSONObject getImage(String imgPath) { return getParam(50, GetImageBase64Str(imgPath)); } //图片转化成base64字符串 public static String GetImageBase64Str(String filePath) {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理 InputStream in = null; byte[] data = null; //读取图片字节数组 try { in = new FileInputStream(filePath); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } //对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data);//返回Base64编码过的字节数组字符串 } public static IDcard_face getIDcard_face(String imgPath){ Map<String, String> headers = new HashMap<String, String>(); //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105 headers.put("Authorization", "APPCODE " + appcode); //根据API的要求,定义相对应的Content-Type headers.put("Content-Type", "application/json; charset=UTF-8"); Map<String, String> querys = new HashMap<String, String>(); String fromPic = imgPath; String toPic = imgPath; try { Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic); } catch (IOException e1) { e1.printStackTrace(); } Map<String, Object> inputs = new HashMap<String, Object>(); Map<String, Object> inputs_map = new HashMap<String, Object>(); inputs_map.put("image", getImage(fromPic)); inputs_map.put("configure", getConfigureSide("face")); List<Map<String, Object>> lst_inputs = new ArrayList<Map<String, Object>>(); lst_inputs.add(inputs_map); inputs.put("inputs", lst_inputs); String bodys = JSON.toJSONString(inputs); try { HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys); if(response.getStatusLine().getStatusCode()==200){ String strResult=""; try { strResult = EntityUtils.toString(response.getEntity()); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } JSONArray outputs = JSONObject.parseObject(strResult).getJSONArray("outputs"); JSONObject outputValue = outputs.getJSONObject(0).getJSONObject("outputValue"); JSONObject idcard = JSONObject.parseObject(outputValue.getString("dataValue")); IDcard_face iDcard_face =idcard.toJavaObject(IDcard_face.class); if(iDcard_face.isSuccess()){ return iDcard_face; } } } catch (Exception e) { e.printStackTrace(); } return null; } public static IDcard_back getIDcard_back(String imgPath){ Map<String, String> headers = new HashMap<String, String>(); //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105 headers.put("Authorization", "APPCODE " + appcode); //根据API的要求,定义相对应的Content-Type headers.put("Content-Type", "application/json; charset=UTF-8"); Map<String, String> querys = new HashMap<String, String>(); String fromPic = imgPath; String toPic = imgPath; try { Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic); } catch (IOException e1) { e1.printStackTrace(); } Map<String, Object> inputs = new HashMap<String, Object>(); Map<String, Object> inputs_map = new HashMap<String, Object>(); inputs_map.put("image", getImage(fromPic)); inputs_map.put("configure", getConfigureSide("back")); List<Map<String, Object>> lst_inputs = new ArrayList<Map<String, Object>>(); lst_inputs.add(inputs_map); inputs.put("inputs", lst_inputs); String bodys = JSON.toJSONString(inputs); try { HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys); if(response.getStatusLine().getStatusCode()==200){ String strResult=""; try { strResult = EntityUtils.toString(response.getEntity()); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } JSONArray outputs = JSONObject.parseObject(strResult).getJSONArray("outputs"); JSONObject outputValue = outputs.getJSONObject(0).getJSONObject("outputValue"); JSONObject idcard = JSONObject.parseObject(outputValue.getString("dataValue")); System.out.println(idcard); IDcard_back iDcard_back =idcard.toJavaObject(IDcard_back.class); System.out.println(iDcard_back.isSuccess()); if(iDcard_back.isSuccess()){ return iDcard_back; } } } catch (Exception e) { e.printStackTrace(); } return null; }public static void main(String[] args) {
String imgPath = "d://face.jpg"; IDcard_face iDcard_face = getIDcard_face(imgPath); System.out.println(iDcard_face.getBirth()); imgPath = "d://back.jpg"; IDcard_back iDcard_back = getIDcard_back(imgPath); System.out.println(iDcard_back.getIssue()); } }