调用阿里云OCR接口识别身份证和户口本

一、controller层代码

package com.wy.gcserver.ocr.controller;

import com.wy.gcserver.ocr.service.AliyunApiOcrService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 阿里云API调用OCR识别Controller层.
 *
 */
@Api(tags = "AliyunApiOcrController", description = "阿里云API调用OCR识别")
@RestController
@RequestMapping(value = "/aliyun/api/ocr")
public class AliyunApiOcrController {

    @Autowired
    private AliyunApiOcrService aliyunApiOcrService;

    /**
     * 获取身份证OCR识别信息.
     *
     * @param job
     * @param image
     * @return
     */
    @ApiOperation("获取身份证OCR识别信息")
    @RequestMapping(value = "/getIdcardOcr",method = RequestMethod.POST)
    public String getIdcardOcr(@RequestParam(value = "job") @ApiParam("正反面标识:face-人脸面/back-国徽面") String job,
                               @RequestParam(value = "image") @ApiParam("图片base64") String image){
        String result = aliyunApiOcrService.getIdcardOcr(job, image);

        return result;
    }

    /**
     * 获取户口本OCR识别信息.
     *
     * @param image
     * @return
     */
    @ApiOperation("获取户口本OCR识别信息")
    @RequestMapping(value = "/getHouseholdOcr",method = RequestMethod.POST)
    public String getHouseholdOcr(@RequestParam(value = "image") @ApiParam("图片base64") String image){
        String result = aliyunApiOcrService.getHouseholdOcr(image);

        return result;
    }

}

二、sevice层代码

package com.wy.gcserver.ocr.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wy.gcserver.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AliyunApiOcrService {
    private static Logger logger = LoggerFactory.getLogger(AliyunApiOcrService.class);

    @Value("${ocr.appCode}")
    private String appCode;

//    @Value("${ocr.host}")
//    private String host;
//
//    @Value("${ocr.path}")
//    private String path;

    private static final String FIELD_OCR_HOST_IDCARD = "http://dm-51.data.aliyun.com";
    private static final String FIELD_OCR_PATH_IDCARD = "/rest/160601/ocr/ocr_idcard.json";

    private static final String FIELD_OCR_HOST_HOUSEHOLD = "https://household.market.alicloudapi.com";
    private static final String FIELD_OCR_PATH_HOUSEHOLD = "/api/predict/ocr_household_register";

    /**
     * 获取header信息.
     *
     * @return
     */
    private Map<String, String> getHeaders(){
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appCode);
        //根据API的要求,定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");

        return headers;
    }

    /**
     * 公共请求方法.
     *
     * @param host
     * @param path
     * @param bodys
     * @return
     */
    private String generalMethod(String host, String path, String bodys){
        String result = "";
        Map<String, String> headers = getHeaders();
        Map<String, String> querys = new HashMap<String, String>();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, "POST", headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                System.out.println("Http code: " + stat);
                System.out.println("http header error msg: " + response.getFirstHeader("X-Ca-Error-Message"));
                System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                return null;
            }

            String res = EntityUtils.toString(response.getEntity());
            JSONObject res_obj = JSON.parseObject(res);

            System.out.println(res_obj.toJSONString());
            result = res_obj.toJSONString();
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return result;
    }

    /**
     * 身份证识别.
     *
     * @param side
     * @param imgBase64
     * @return
     */
    public String getIdcardOcr(String side, String imgBase64) {
        Map<String, String> headers = getHeaders();

        Map<String, String> querys = new HashMap<String, String>();

        //configure配置
        JSONObject configObj = new JSONObject();
        configObj.put("side", side);
        String config_str = configObj.toString();

        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", imgBase64);
        if (configObj.size() > 0) {
            requestObj.put("configure", config_str);
        }
        String bodys = requestObj.toString();
        String result = generalMethod(FIELD_OCR_HOST_IDCARD, FIELD_OCR_PATH_IDCARD, bodys);

        return result;
    }

    /**
     * 户口本识别.
     *
     * @param imgBase64
     * @return
     */
    public String getHouseholdOcr(String imgBase64){
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", imgBase64);
        String bodys = requestObj.toString();
        String result = generalMethod(FIELD_OCR_HOST_HOUSEHOLD, FIELD_OCR_PATH_HOUSEHOLD, bodys);

        return result;
    }

}

三、附件
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值