當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring Boot笔记-使用RestTemplate优雅的调用百度ORC接口
生活随笔
收集整理的這篇文章主要介紹了
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接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java文档阅读笔记-C3P0连接池的使
- 下一篇: Qt文档阅读笔记-void QObjec