Java对接微信OCR上传图片身份证识别

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); 
}
}}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值