Spring Boot笔记-使用RestTemplate优雅的调用百度ORC接口

140 篇文章 4 订阅

这里ORC是干嘛的就不说了。

要识别的图片如下:

Java关键源码如下:

@Service
public class TestServer {

    @Autowired
    private RestTemplate restTemplate;

    private static String grantType = "client_credentials";
    private static String clientId = "it1995it1995it1995it1995it1995it1995";
    private static String clientSecret = "it1995it1995it1995it1995it1995it1995";

    protected String readFileWithBase64(String fileName){

        String ret = null;

        try{

            File file = new File(fileName);
            Long fileLength = file.length();
            byte[] fileContent = new byte[fileLength.intValue()];

            FileInputStream in = new FileInputStream(file);
            in.read(fileContent);
            in.close();

            //进行Base64编码
            ret = Base64.getEncoder().encodeToString(fileContent);
        }
        catch (IOException e){

            e.printStackTrace();
        }

        return ret;
    }

    public void test(){

        //获取access_token
        String accessUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=%0&client_id=%1&client_secret=%2";
        accessUrl = accessUrl.replace("%0", grantType).replace("%1", clientId).replace("%2", clientSecret);

        ResponseEntity<String> forEntity = restTemplate.getForEntity(accessUrl, String.class);
        Map<String, String> tokenRetMap = JSON.parseObject(forEntity.getBody(), Map.class);
        if(!tokenRetMap.containsKey("access_token")){

            System.out.println("ERROR:" + forEntity.getBody());
            return;
        }

        String access_token = tokenRetMap.get("access_token");

        //读取图片
        String fileContent = readFileWithBase64("C:\\Users\\Administrator\\Desktop\\test\\1.jpg");

        //构造参数
        String orcUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=%0";
        orcUrl = orcUrl.replace("%0", access_token);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");

        MultiValueMap<String, Object> paraMap = new LinkedMultiValueMap<>();
        paraMap.put("image", Collections.singletonList(fileContent));

        String orcRet = restTemplate.postForObject(orcUrl, new HttpEntity<>(paraMap, headers), String.class);
        System.out.println(orcRet);


        System.out.println("over");
    }
}

程序运行截图如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值