欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

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

发布时间:2025/3/15 javascript 59 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Spring Boot笔记-使用RestTemplate优雅的调用百度ORC接口 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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

要识别的图片如下:

Java关键源码如下:

@Service public class TestServer {@Autowiredprivate 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_tokenString 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");} }

程序运行截图如下:

总结

以上是生活随笔为你收集整理的Spring Boot笔记-使用RestTemplate优雅的调用百度ORC接口的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。