API地址:https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/img-ocr/ocr/idCardOCR.html
具体流程:1 获取accessToken 地址:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s
其中appid和secret为小程序appid以及秘钥。
2 进行具体识别 地址:https://api.weixin.qq.com/cv/ocr/idcard?type=photo&access_token=
最大的坑:传参img需要模拟表单提交
代码如下
HttpEntity httpEntity = MultipartEntityBuilder.create()
//模拟表单提交文件
.addPart("img", d)
.build();
完整代码如下(大括号可能多一个少一个):
public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, Boolean isIdCard) throws Exception {
try {
IdCardDto idCardDto = new IdCardDto();
//身份证正面传true,默认false
if (isIdCard) {
String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId, secret);
JSONObject token = JSON.parseObject(HttpUtil.get(token_url));
String url = "https://api.weixin.qq.com/cv/ocr/idcard?type=photo&access_token=" + token.getString("access_token");
HttpPost httpPost = new HttpPost(url);
File f = new File(RuoYiConfig.getProfile() + file.getOriginalFilename());
//解决输入流无法重复读取问题
FileCopyUtils.copy(file.getInputStream(), Files.newOutputStream(Paths.get(RuoYiConfig.getProfile() + file.getOriginalFilename())));
FileBody d = new FileBody(f, ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename());
HttpEntity httpEntity = MultipartEntityBuilder.create()
//模拟表单提交文件
.addPart("img", d)
.build();
httpPost.setEntity(httpEntity);
HttpResponse response = HttpClientBuilder.create().build().execute(httpPost);
String s = EntityUtils.toString(response.getEntity());
cn.hutool.json.JSONObject object = JSONUtil.parseObj(s);
return AjaxResult.success(object);
}
}}
1730

被折叠的 条评论
为什么被折叠?



