Java百度身份证识别接口实现【配置即用】
第一步:申请百度 OCR 身份证识别 API
注册百度智能云:https://cloud.baidu.com/
开通 身份证识别 OCR 服务 【直接搜索】
创建应用,获取:
API Key
Secret Key
第二步:Java依赖
<dependencies><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.9.3</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.10</version></dependency>
</dependencies>
第三步:Java程序
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;public class IdCardRecognizer {private static final String API_KEY = "你的API_KEY";private static final String SECRET_KEY = "你的SECRET_KEY";private static final String OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";public static void main(String[] args) throws IOException {String accessToken = getAccessToken();File imageFile = new File("idcard.jpg"); // 替换为你的图片路径String base64Image = Base64.getEncoder().encodeToString(Files.readAllBytes(imageFile.toPath()));OkHttpClient client = new OkHttpClient();RequestBody body = new FormBody.Builder().add("image", base64Image).add("id_card_side", "front") // "front" 正面,"back" 反面.build();Request request = new Request.Builder().url(OCR_URL + "?access_token=" + accessToken).post(body).addHeader("Content-Type", "application/x-www-form-urlencoded").build();Response response = client.newCall(request).execute();String json = response.body().string();JsonObject result = JsonParser.parseString(json).getAsJsonObject().getAsJsonObject("words_result");System.out.println("姓名: " + result.getAsJsonObject("姓名").get("words").getAsString());System.out.println("性别: " + result.getAsJsonObject("性别").get("words").getAsString());System.out.println("民族: " + result.getAsJsonObject("民族").get("words").getAsString());System.out.println("出生: " + result.getAsJsonObject("出生").get("words").getAsString());System.out.println("住址: " + result.getAsJsonObject("住址").get("words").getAsString());System.out.println("公民身份号码: " + result.getAsJsonObject("公民身份号码").get("words").getAsString());}// 获取AccessToken(可缓存一天)private static String getAccessToken() throws IOException {OkHttpClient client = new OkHttpClient();String url = "https://aip.baidubce.com/oauth/2.0/token"+ "?grant_type=client_credentials"+ "&client_id=" + API_KEY+ "&client_secret=" + SECRET_KEY;Request request = new Request.Builder().url(url).build();Response response = client.newCall(request).execute();String json = response.body().string();JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();return jsonObject.get("access_token").getAsString();}
}