• Java 百度智能云(身份证识别)


    第一步:是要拿到access_token这个秘钥。

    参数

    access_token

    通过API Key和Secret Key获取的access_token,参考“Access Token获取

    AIP:https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials

    1. static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    2. MediaType mediaType = MediaType.parse("application/json");
    3. okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, "&client_id="+API_KEY+"&client_secret="+SECRET_KEY);
    4. Request request = new Request.Builder()
    5. .url("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials")
    6. .method("POST", body)
    7. .addHeader("Content-Type", "application/json")
    8. .addHeader("Accept", "application/json")
    9. .build();
    10. Response response = null;
    11. try {
    12. response = HTTP_CLIENT.newCall(request).execute();
    13. } catch (IOException e) {
    14. throw new RuntimeException(e);
    15. }
    16. //只会调用一次
    17. // System.out.println(response.body().string());
    18. try {
    19. JSONObject jsonObject = JSONObject.parseObject(response.body().string());
    20. String accessToken = jsonObject.getString("access_token");
    21. System.out.println("accessToken="+accessToken);

    第二步:上传身份证,验证身份证

    请求参数:

    1. // 请求url
    2. String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
    3. //图片地址
    4. String filePath = pats;
    5. System.out.println("filePath=" + filePath);
    6. // String filePath = "C://Users/29291/Desktop/12.png";
    7. //String filePath = "https://gulimall-vues.oss-cn-chengdu.aliyuncs.com/11.jpg";
    8. byte[] imgData = FileUtil.readFileByBytes(filePath);
    9. String imgStr = Base64Util.encode(imgData);
    10. String imgParam = URLEncoder.encode(imgStr, "UTF-8");
    11. //拼接参数
    12. String param = "id_card_side=" + "back" + "&image=" + imgParam + "&detect_risk=" + "true";
    13. // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
    14. String accessTokens = accessToken;
    15. String result = HttpUtils.post(url, accessTokens, param);
    16. System.out.println("result=" + result);
    17. JSONObject jsonObjects = JSONObject.parseObject(result);
    18. String riskType = jsonObjects.getString("risk_type");
    19. System.out.println("riskType=" + riskType);
    20. if (!riskType.equals("normal")) {
    21. new File(pats).delete();
    22. System.out.println("请上传有效身份证");
    23. return R.error("请上传有效身份证");
    24. }
    25. //身份证信息
    26. String name = jsonObjects.getJSONObject("words_result").getJSONObject("姓名").getString("words");
    27. System.out.println("name=" + name);
    28. //判断信息是否一致
    29. if (!name.equals(fullName)) {
    30. new File(pats).delete();
    31. return R.error("信息错误,请重新认证");
    32. }
    33. String nation = jsonObjects.getJSONObject("words_result").getJSONObject("民族").getString("words");
    34. String address = jsonObjects.getJSONObject("words_result").getJSONObject("住址").getString("words");
    35. String card = jsonObjects.getJSONObject("words_result").getJSONObject("公民身份号码").getString("words");
    36. String birthday = jsonObjects.getJSONObject("words_result").getJSONObject("出生").getString("words");
    37. String sex = jsonObjects.getJSONObject("words_result").getJSONObject("性别").getString("words");
    38. new File(pats).delete();
    39. Courier courier1=new Courier();
    40. courier1.setIdentityStatus("1");
    41. courier1.setCourierId(courierId);
    42. courierService.updateCourier(courier1);

    参数

    是否必选

    类型

    可选值范围

    说明

    image

    和url二选一

    string

    -

    图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/jpeg/png/bmp格式

    url

    和image二选一

    string

    -

    图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/jpeg/png/bmp格式,当image字段存在时url字段失效
    请注意关闭URL防盗链

    id_card_side

    string

    front/back

    -front:身份证含照片的一面
    -back:身份证带国徽的一面
    自动检测身份证正反面,如果传参指定方向与图片相反,支持正常识别,返回参数image_status字段为"reversed_side"

    detect_risk

    string

    true/false

    是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)检测功能,默认不开启,即:false。
    - true:开启,请查看返回参数risk_type;
    - false:不开启

    detect_quality

    string

    true/false

    是否开启身份证质量类型(边框/四角不完整、头像或关键字段被遮挡/马赛克)检测功能,默认不开启,即:false。
    - true:开启,请查看返回参数card_quality;
    - false:不开启

    detect_photo

    string

    true/false

    是否检测头像内容,默认不检测。可选值:true-检测头像并返回头像的 base64 编码及位置信息

    detect_card

    string

    true/false

    是否检测身份证进行裁剪,默认不检测。可选值:true-检测身份证并返回证照的 base64 编码及位置信息

    1. // 请求url
    2. String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
    3. //图片地址
    4. String filePath = pats;
    5. System.out.println("filePath=" + filePath);
    6. // String filePath = "C://Users/29291/Desktop/12.png";
    7. //String filePath = "https://gulimall-vues.oss-cn-chengdu.aliyuncs.com/11.jpg";
    8. byte[] imgData = FileUtil.readFileByBytes(filePath);
    9. String imgStr = Base64Util.encode(imgData);
    10. String imgParam = URLEncoder.encode(imgStr, "UTF-8");
    11. //拼接参数
    12. String param = "id_card_side=" + "back" + "&image=" + imgParam + "&detect_risk=" + "true";
    13. // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
    14. String accessTokens = accessToken;
    15. String result = HttpUtils.post(url, accessTokens, param);
    16. System.out.println("result=" + result);
    17. JSONObject jsonObjects = JSONObject.parseObject(result);
    18. String riskType = jsonObjects.getString("risk_type");
    19. System.out.println("riskType=" + riskType);
    20. if (!riskType.equals("normal")) {
    21. new File(pats).delete();
    22. System.out.println("请上传有效身份证");
    23. return R.error("请上传有效身份证");
    24. }
    25. //身份证信息
    26. String name = jsonObjects.getJSONObject("words_result").getJSONObject("姓名").getString("words");
    27. System.out.println("name=" + name);
    28. //判断信息是否一致
    29. if (!name.equals(fullName)) {
    30. new File(pats).delete();
    31. return R.error("信息错误,请重新认证");
    32. }
    33. String nation = jsonObjects.getJSONObject("words_result").getJSONObject("民族").getString("words");
    34. String address = jsonObjects.getJSONObject("words_result").getJSONObject("住址").getString("words");
    35. String card = jsonObjects.getJSONObject("words_result").getJSONObject("公民身份号码").getString("words");
    36. String birthday = jsonObjects.getJSONObject("words_result").getJSONObject("出生").getString("words");
    37. String sex = jsonObjects.getJSONObject("words_result").getJSONObject("性别").getString("words");
    38. new File(pats).delete();
    39. Courier courier1=new Courier();
    40. courier1.setIdentityStatus("1");
    41. courier1.setCourierId(courierId);
    42. courierService.updateCourier(courier1);
    1. package com.td.utils;
    2. import java.io.BufferedReader;
    3. import java.io.DataOutputStream;
    4. import java.io.InputStreamReader;
    5. import java.net.HttpURLConnection;
    6. import java.net.URL;
    7. import java.util.List;
    8. import java.util.Map;
    9. /**
    10. * http 工具类
    11. */
    12. public class HttpUtils {
    13. public static String post(String requestUrl, String accessToken, String params)
    14. throws Exception {
    15. String contentType = "application/x-www-form-urlencoded";
    16. return HttpUtils.post(requestUrl, accessToken, contentType, params);
    17. }
    18. public static String post(String requestUrl, String accessToken, String contentType, String params)
    19. throws Exception {
    20. String encoding = "UTF-8";
    21. if (requestUrl.contains("nlp")) {
    22. encoding = "GBK";
    23. }
    24. return HttpUtils.post(requestUrl, accessToken, contentType, params, encoding);
    25. }
    26. public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
    27. throws Exception {
    28. String url = requestUrl + "?access_token=" + accessToken;
    29. return HttpUtils.postGeneralUrl(url, contentType, params, encoding);
    30. }
    31. public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
    32. throws Exception {
    33. URL url = new URL(generalUrl);
    34. // 打开和URL之间的连接
    35. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    36. connection.setRequestMethod("POST");
    37. // 设置通用的请求属性
    38. connection.setRequestProperty("Content-Type", contentType);
    39. connection.setRequestProperty("Connection", "Keep-Alive");
    40. connection.setUseCaches(false);
    41. connection.setDoOutput(true);
    42. connection.setDoInput(true);
    43. // 得到请求的输出流对象
    44. DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    45. out.write(params.getBytes(encoding));
    46. out.flush();
    47. out.close();
    48. // 建立实际的连接
    49. connection.connect();
    50. // 获取所有响应头字段
    51. Map> headers = connection.getHeaderFields();
    52. // 遍历所有的响应头字段
    53. for (String key : headers.keySet()) {
    54. System.err.println(key + "--->" + headers.get(key));
    55. }
    56. // 定义 BufferedReader输入流来读取URL的响应
    57. BufferedReader in = null;
    58. in = new BufferedReader(
    59. new InputStreamReader(connection.getInputStream(), encoding));
    60. String result = "";
    61. String getLine;
    62. while ((getLine = in.readLine()) != null) {
    63. result += getLine;
    64. }
    65. in.close();
    66. System.err.println("result:" + result);
    67. return result;
    68. }
    69. }
    1. package com.td.utils;
    2. import java.io.*;
    3. /**
    4. * 文件读取工具类
    5. */
    6. public class FileUtil {
    7. /**
    8. * 读取文件内容,作为字符串返回
    9. */
    10. public static String readFileAsString(String filePath) throws IOException {
    11. File file = new File(filePath);
    12. if (!file.exists()) {
    13. throw new FileNotFoundException(filePath);
    14. }
    15. if (file.length() > 1024 * 1024 * 1024) {
    16. throw new IOException("File is too large");
    17. }
    18. StringBuilder sb = new StringBuilder((int) (file.length()));
    19. // 创建字节输入流
    20. FileInputStream fis = new FileInputStream(filePath);
    21. // 创建一个长度为10240的Buffer
    22. byte[] bbuf = new byte[10240];
    23. // 用于保存实际读取的字节数
    24. int hasRead = 0;
    25. while ( (hasRead = fis.read(bbuf)) > 0 ) {
    26. sb.append(new String(bbuf, 0, hasRead));
    27. }
    28. fis.close();
    29. return sb.toString();
    30. }
    31. /**
    32. * 根据文件路径读取byte[] 数组
    33. */
    34. public static byte[] readFileByBytes(String filePath) throws IOException {
    35. File file = new File(filePath);
    36. if (!file.exists()) {
    37. throw new FileNotFoundException(filePath);
    38. } else {
    39. ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
    40. BufferedInputStream in = null;
    41. try {
    42. in = new BufferedInputStream(new FileInputStream(file));
    43. short bufSize = 1024;
    44. byte[] buffer = new byte[bufSize];
    45. int len1;
    46. while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
    47. bos.write(buffer, 0, len1);
    48. }
    49. byte[] var7 = bos.toByteArray();
    50. return var7;
    51. } finally {
    52. try {
    53. if (in != null) {
    54. in.close();
    55. }
    56. } catch (IOException var14) {
    57. var14.printStackTrace();
    58. }
    59. bos.close();
    60. }
    61. }
    62. }
    63. }
    1. package com.td.utils;
    2. /**
    3. * Base64 工具类
    4. */
    5. public class Base64Util {
    6. private static final char last2byte = (char) Integer.parseInt("00000011", 2);
    7. private static final char last4byte = (char) Integer.parseInt("00001111", 2);
    8. private static final char last6byte = (char) Integer.parseInt("00111111", 2);
    9. private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
    10. private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
    11. private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
    12. private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
    13. public Base64Util() {
    14. }
    15. public static String encode(byte[] from) {
    16. StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
    17. int num = 0;
    18. char currentByte = 0;
    19. int i;
    20. for (i = 0; i < from.length; ++i) {
    21. for (num %= 8; num < 8; num += 6) {
    22. switch (num) {
    23. case 0:
    24. currentByte = (char) (from[i] & lead6byte);
    25. currentByte = (char) (currentByte >>> 2);
    26. case 1:
    27. case 3:
    28. case 5:
    29. default:
    30. break;
    31. case 2:
    32. currentByte = (char) (from[i] & last6byte);
    33. break;
    34. case 4:
    35. currentByte = (char) (from[i] & last4byte);
    36. currentByte = (char) (currentByte << 2);
    37. if (i + 1 < from.length) {
    38. currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
    39. }
    40. break;
    41. case 6:
    42. currentByte = (char) (from[i] & last2byte);
    43. currentByte = (char) (currentByte << 4);
    44. if (i + 1 < from.length) {
    45. currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
    46. }
    47. }
    48. to.append(encodeTable[currentByte]);
    49. }
    50. }
    51. if (to.length() % 4 != 0) {
    52. for (i = 4 - to.length() % 4; i > 0; --i) {
    53. to.append("=");
    54. }
    55. }
    56. return to.toString();
    57. }
    58. }

  • 相关阅读:
    在Mac中管理多版本 java——安装和使用 jenv
    致力于成为某个细分行业最牛逼的程序员,您该如何实现?
    shiro的简单介绍
    APISIX 在君润人力云原生平台的架构实践
    开放式运动耳机哪款好,盘点几款目前最好的开放式耳机分享
    不明身份人员如何确认?幼儿园出新招了
    第5章-宏观业务分析方法-5.4-因子分析
    一个奇葩的线上问题,导致我排查了一天!
    python可视化分析(八)-绘制双坐标系时间序列图
    智能问答技术在百度搜索中的应用
  • 原文地址:https://blog.csdn.net/m0_55699184/article/details/130890200