使用阿里身份证识别接口(使用appkey和secret)
推荐你看一下七牛的文档<编程模型 - 七牛开发者中心>, 明确提出需要一个业务服务器来生成各种token.
同时总结了几个关键的原则:
- 整个架构中需要一个业务服务器组件。
- 无论如何,访问密钥(AK/SK)均不得包含在客户端的分发包中(如二进制代码、配置文件或网页中)。
- SecretKey不得在任何场景中的公网上传输,更不得传输到客户端。
- 业务服务器端应维持一个用于管理资源元数据的数据库和一个用于管理最终用户账号信息的数据库。
- 原则上客户端和七牛云存储之间的交互只有上传和下载,不应使用任何其他的API。
作者:aaashun
链接:https://www.zhihu.com/question/24034365/answer/147662419
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
- package reco;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import org.apache.commons.codec.binary.Base64;
- import org.json.JSONObject;
- import org.json.JSONArray;
- import org.json.JSONException;
- public class IDcard {
-
-
-
- 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;
- }
-
-
-
- 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 void main(String[] args) {
- String imgFile = "E:/cxf/develop-workspace-new/upadmin/temp/1490854550779.jpg";
- String serviceURL = "https://dm-51.data.aliyun.com";
- String akID = "你的appkey";
- String akSecret = "你的secret";
-
- 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();
- imgBase64 = new String(Base64.encodeBase64(content));
- } catch (IOException e) {
- e.printStackTrace();
- return;
- }
-
- JSONObject requestObj = new JSONObject();
- try {
- JSONObject configObj = new JSONObject();
- JSONObject obj = new JSONObject();
- JSONArray inputArray = new JSONArray();
- configObj.put("side", "face");
- obj.put("image", getParam(50, imgBase64));
- obj.put("configure", getParam(50, configObj.toString()));
- inputArray.put(obj);
- requestObj.put("inputs", inputArray);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- String body = requestObj.toString();
- String bodys = "{\"inputs\": [{\"image\": {\"dataType\": 50,\"dataValue\": \""+123+"\"},\"configure\": {\"dataType\": 50,\"dataValue\": \"{\\\"side\\\":\\\"face\\\",}\"}}]}";
-
- String result = Sender.sendPost(serviceURL, bodys, akID, akSecret);
- System.out.println(result);
-
- try {
- JSONObject resultObj = new JSONObject(result);
- JSONArray outputArray = resultObj.getJSONArray("outputs");
- String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
- JSONObject out = new JSONObject(output);
- if (out.getBoolean("success")) {
- String addr = out.getString("address");
- String name = out.getString("name");
- String num = out.getString("num");
- System.out.printf(" name : %s \n num : %s\n address : %s\n", name, num, addr);
- } else {
- System.out.println("predict error");
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- }
- package reco;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
- import java.security.MessageDigest;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.Locale;
- import javax.crypto.spec.SecretKeySpec;
- import sun.misc.BASE64Encoder;
- import javax.crypto.Mac;
- public class Sender {
-
-
-
- public static String MD5Base64(String s) {
- if (s == null)
- return null;
- String encodeStr = "";
- byte[] utfBytes = s.getBytes();
- MessageDigest mdTemp;
- try {
- mdTemp = MessageDigest.getInstance("MD5");
- mdTemp.update(utfBytes);
- byte[] md5Bytes = mdTemp.digest();
- BASE64Encoder b64Encoder = new BASE64Encoder();
- encodeStr = b64Encoder.encode(md5Bytes);
- } catch (Exception e) {
- throw new Error("Failed to generate MD5 : " + e.getMessage());
- }
- return encodeStr;
- }
-
-
-
- public static String HMACSha1(String data, String key) {
- String result;
- try {
-
-
- SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
- Mac mac = Mac.getInstance("HmacSHA1");
- mac.init(signingKey);
- byte[] rawHmac = mac.doFinal(data.getBytes());
- result = (new BASE64Encoder()).encode(rawHmac);
- } catch (Exception e) {
- throw new Error("Failed to generate HMAC : " + e.getMessage());
- }
- return result;
- }
-
-
-
- public static String toGMTString(Date date) {
- SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);
- df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
- return df.format(date);
- }
-
-
-
- public static String sendPost(String url, String body, String ak_id, String ak_secret) {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try {
- URL realUrl = new URL(url);
-
-
-
- String method = "POST";
- String accept = "json";
- String content_type = "application/json";
- String path = realUrl.getFile();
- String date = toGMTString(new Date());
-
- String bodyMd5 = MD5Base64(body);
- String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n"
- + path;
-
- String signature = HMACSha1(stringToSign, ak_secret);
-
- String authHeader = "Dataplus " + ak_id + ":" + signature;
-
- URLConnection conn = realUrl.openConnection();
-
- conn.setRequestProperty("accept", accept);
- conn.setRequestProperty("content-type", content_type);
- conn.setRequestProperty("date", date);
- conn.setRequestProperty("Authorization", authHeader);
- conn.setRequestProperty("Accept-Charset", "UTF-8");
-
- conn.setDoOutput(true);
- conn.setDoInput(true);
-
- out = new PrintWriter(conn.getOutputStream());
-
- out.print(body);
-
- out.flush();
-
- InputStream is;
- HttpURLConnection httpconn = (HttpURLConnection) conn;
- if (httpconn.getResponseCode() == 200) {
- is = httpconn.getInputStream();
- } else {
- is = httpconn.getErrorStream();
- }
- InputStreamReader sr = new InputStreamReader(is,"utf-8");
- in = new BufferedReader(sr);
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- System.out.println("发送 POST 请求出现异常!" + e);
- e.printStackTrace();
- }
-
- finally {
- try {
- if (out != null) {
- out.close();
- }
- if (in != null) {
- in.close();
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- return result;
- }
- }
- 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 {
-
-
-
-
-
-
-
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
-
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
-
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
-
-
-
-
-
-
- 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);
- }
- }
- }