import com.ltkj.web.config.IdcardUtil.IdcardUtil; import okhttp3.*; import org.json.JSONObject; import javax.imageio.stream.FileImageInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URLEncoder; /** * 身份证识别 */ public class Idcard { public static String idcard() { // 请求url String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"; try { // 本地文件路径 String filePath = "C:\\Users\\w\\Pictures\\Saved Pictures\\微信图片_20230317105940.jpg"; byte[] imgData = readImageFile(filePath); String imgStr = IdcardUtil.encode(imgData); String imgParam = URLEncoder.encode(imgStr, "UTF-8"); String param = "id_card_side=" + "front" + "&image=" + imgParam; // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。 String accessToken = getAccessToken(); String result = IdcardUtil.post(url, accessToken,param); System.out.println(result); return result; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 从用户的AK,SK生成鉴权签名(Access Token) * * @return 鉴权签名(Access Token) * @throws IOException IO异常 */ static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build(); static String getAccessToken() throws IOException { MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" +"mRFH6G6ILvXCpy1Pwgs1WZXW" + "&client_secret=" +"1o4DUvPuiGzPF44Y4gSsIrKMfn1awDhC"); Request request = new Request.Builder() .url("https://aip.baidubce.com/oauth/2.0/token") .method("POST", body) .addHeader("Content-Type", "application/x-www-form-urlencoded") .build(); Response response = HTTP_CLIENT.newCall(request).execute(); return new JSONObject(response.body().string()).getString("access_token"); } /** 将图像转为二进制数组 * @param path * @return */ public static byte[] readImageFile(String path) { byte[] data = null; FileImageInputStream input = null; try { input = new FileImageInputStream(new File(path)); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int numBytesRead = 0; while ((numBytesRead = input.read(buf)) != -1) { output.write(buf, 0, numBytesRead); } data = output.toByteArray(); output.close(); input.close(); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); } catch (IOException ex1) { ex1.printStackTrace(); } return data; } public static void main(String[] args) { Idcard.idcard(); } }