第一步:是要拿到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
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("application/json");
okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, "&client_id="+API_KEY+"&client_secret="+SECRET_KEY);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
Response response = null;
try {
response = HTTP_CLIENT.newCall(request).execute();
} catch (IOException e) {
throw new RuntimeException(e);
}
//只会调用一次
// System.out.println(response.body().string());
try {
JSONObject jsonObject = JSONObject.parseObject(response.body().string());
String accessToken = jsonObject.getString("access_token");
System.out.println("accessToken="+accessToken);
第二步:上传身份证,验证身份证
请求参数:
// 请求url
String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
//图片地址
String filePath = pats;
System.out.println("filePath=" + filePath);
// String filePath = "C://Users/29291/Desktop/12.png";
//String filePath = "https://gulimall-vues.oss-cn-chengdu.aliyuncs.com/11.jpg";
byte[] imgData = FileUtil.readFileByBytes(filePath);
String imgStr = Base64Util.encode(imgData);
String imgParam = URLEncoder.encode(imgStr, "UTF-8");
//拼接参数
String param = "id_card_side=" + "back" + "&image=" + imgParam + "&detect_risk=" + "true";
// 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
String accessTokens = accessToken;
String result = HttpUtils.post(url, accessTokens, param);
System.out.println("result=" + result);
JSONObject jsonObjects = JSONObject.parseObject(result);
String riskType = jsonObjects.getString("risk_type");
System.out.println("riskType=" + riskType);
if (!riskType.equals("normal")) {
new File(pats).delete();
System.out.println("请上传有效身份证");
return R.error("请上传有效身份证");
}
//身份证信息
String name = jsonObjects.getJSONObject("words_result").getJSONObject("姓名").getString("words");
System.out.println("name=" + name);
//判断信息是否一致
if (!name.equals(fullName)) {
new File(pats).delete();
return R.error("信息错误,请重新认证");
}
String nation = jsonObjects.getJSONObject("words_result").getJSONObject("民族").getString("words");
String address = jsonObjects.getJSONObject("words_result").getJSONObject("住址").getString("words");
String card = jsonObjects.getJSONObject("words_result").getJSONObject("公民身份号码").getString("words");
String birthday = jsonObjects.getJSONObject("words_result").getJSONObject("出生").getString("words");
String sex = jsonObjects.getJSONObject("words_result").getJSONObject("性别").getString("words");
new File(pats).delete();
Courier courier1=new Courier();
courier1.setIdentityStatus("1");
courier1.setCourierId(courierId);
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字段失效 |
id_card_side |
是 |
string |
front/back |
-front:身份证含照片的一面 |
detect_risk |
否 |
string |
true/false |
是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)检测功能,默认不开启,即:false。 |
detect_quality |
否 |
string |
true/false |
是否开启身份证质量类型(边框/四角不完整、头像或关键字段被遮挡/马赛克)检测功能,默认不开启,即:false。 |
detect_photo |
否 |
string |
true/false |
是否检测头像内容,默认不检测。可选值:true-检测头像并返回头像的 base64 编码及位置信息 |
detect_card |
否 |
string |
true/false |
是否检测身份证进行裁剪,默认不检测。可选值:true-检测身份证并返回证照的 base64 编码及位置信息 |
// 请求url
String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
//图片地址
String filePath = pats;
System.out.println("filePath=" + filePath);
// String filePath = "C://Users/29291/Desktop/12.png";
//String filePath = "https://gulimall-vues.oss-cn-chengdu.aliyuncs.com/11.jpg";
byte[] imgData = FileUtil.readFileByBytes(filePath);
String imgStr = Base64Util.encode(imgData);
String imgParam = URLEncoder.encode(imgStr, "UTF-8");
//拼接参数
String param = "id_card_side=" + "back" + "&image=" + imgParam + "&detect_risk=" + "true";
// 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
String accessTokens = accessToken;
String result = HttpUtils.post(url, accessTokens, param);
System.out.println("result=" + result);
JSONObject jsonObjects = JSONObject.parseObject(result);
String riskType = jsonObjects.getString("risk_type");
System.out.println("riskType=" + riskType);
if (!riskType.equals("normal")) {
new File(pats).delete();
System.out.println("请上传有效身份证");
return R.error("请上传有效身份证");
}
//身份证信息
String name = jsonObjects.getJSONObject("words_result").getJSONObject("姓名").getString("words");
System.out.println("name=" + name);
//判断信息是否一致
if (!name.equals(fullName)) {
new File(pats).delete();
return R.error("信息错误,请重新认证");
}
String nation = jsonObjects.getJSONObject("words_result").getJSONObject("民族").getString("words");
String address = jsonObjects.getJSONObject("words_result").getJSONObject("住址").getString("words");
String card = jsonObjects.getJSONObject("words_result").getJSONObject("公民身份号码").getString("words");
String birthday = jsonObjects.getJSONObject("words_result").getJSONObject("出生").getString("words");
String sex = jsonObjects.getJSONObject("words_result").getJSONObject("性别").getString("words");
new File(pats).delete();
Courier courier1=new Courier();
courier1.setIdentityStatus("1");
courier1.setCourierId(courierId);
courierService.updateCourier(courier1);
package com.td.utils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* http 工具类
*/
public class HttpUtils {
public static String post(String requestUrl, String accessToken, String params)
throws Exception {
String contentType = "application/x-www-form-urlencoded";
return HttpUtils.post(requestUrl, accessToken, contentType, params);
}
public static String post(String requestUrl, String accessToken, String contentType, String params)
throws Exception {
String encoding = "UTF-8";
if (requestUrl.contains("nlp")) {
encoding = "GBK";
}
return HttpUtils.post(requestUrl, accessToken, contentType, params, encoding);
}
public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
throws Exception {
String url = requestUrl + "?access_token=" + accessToken;
return HttpUtils.postGeneralUrl(url, contentType, params, encoding);
}
public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
throws Exception {
URL url = new URL(generalUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
// 得到请求的输出流对象
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(params.getBytes(encoding));
out.flush();
out.close();
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> headers = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : headers.keySet()) {
System.err.println(key + "--->" + headers.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
in = new BufferedReader(
new InputStreamReader(connection.getInputStream(), encoding));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
System.err.println("result:" + result);
return result;
}
}
package com.td.utils;
import java.io.*;
/**
* 文件读取工具类
*/
public class FileUtil {
/**
* 读取文件内容,作为字符串返回
*/
public static String readFileAsString(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
}
if (file.length() > 1024 * 1024 * 1024) {
throw new IOException("File is too large");
}
StringBuilder sb = new StringBuilder((int) (file.length()));
// 创建字节输入流
FileInputStream fis = new FileInputStream(filePath);
// 创建一个长度为10240的Buffer
byte[] bbuf = new byte[10240];
// 用于保存实际读取的字节数
int hasRead = 0;
while ( (hasRead = fis.read(bbuf)) > 0 ) {
sb.append(new String(bbuf, 0, hasRead));
}
fis.close();
return sb.toString();
}
/**
* 根据文件路径读取byte[] 数组
*/
public static byte[] readFileByBytes(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
short bufSize = 1024;
byte[] buffer = new byte[bufSize];
int len1;
while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
bos.write(buffer, 0, len1);
}
byte[] var7 = bos.toByteArray();
return var7;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException var14) {
var14.printStackTrace();
}
bos.close();
}
}
}
}
package com.td.utils;
/**
* Base64 工具类
*/
public class Base64Util {
private static final char last2byte = (char) Integer.parseInt("00000011", 2);
private static final char last4byte = (char) Integer.parseInt("00001111", 2);
private static final char last6byte = (char) Integer.parseInt("00111111", 2);
private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
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', '+', '/'};
public Base64Util() {
}
public static String encode(byte[] from) {
StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
int num = 0;
char currentByte = 0;
int i;
for (i = 0; i < from.length; ++i) {
for (num %= 8; num < 8; num += 6) {
switch (num) {
case 0:
currentByte = (char) (from[i] & lead6byte);
currentByte = (char) (currentByte >>> 2);
case 1:
case 3:
case 5:
default:
break;
case 2:
currentByte = (char) (from[i] & last6byte);
break;
case 4:
currentByte = (char) (from[i] & last4byte);
currentByte = (char) (currentByte << 2);
if (i + 1 < from.length) {
currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
}
break;
case 6:
currentByte = (char) (from[i] & last2byte);
currentByte = (char) (currentByte << 4);
if (i + 1 < from.length) {
currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
}
}
to.append(encodeTable[currentByte]);
}
}
if (to.length() % 4 != 0) {
for (i = 4 - to.length() % 4; i > 0; --i) {
to.append("=");
}
}
return to.toString();
}
}