Java调用百度OCR文字识别的接口

调用百度OCR文字识别的接口,来自于百度官网,亲测可以使用

  • 跳转链接
  • FileUtil的下载链接
  • Base64Util下载链接
  • HttpUtil下载链接
  • GsonUtils下载链接
  • Accurate.java文件
package com.baidu.ai.aip;import com.baidu.ai.aip.utils.Base64Util;
import com.baidu.ai.aip.utils.FileUtil;
import com.baidu.ai.aip.utils.HttpUtil;import java.net.URLEncoder;/**
* 通用文字识别(高精度含位置版)
*/
public class Accurate {/*** 重要提示代码中所需工具类* FileUtil,Base64Util,HttpUtil,GsonUtils请从* https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72* https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2* https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3* https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3* 下载*/public static String accurate() {// 请求urlString url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate";try {// 本地文件路径String filePath = "[本地文件路径]";byte[] imgData = FileUtil.readFileByBytes(filePath);String imgStr = Base64Util.encode(imgData);String imgParam = URLEncoder.encode(imgStr, "UTF-8");String param = "image=" + imgParam;// 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。String accessToken = "[调用鉴权接口获取的token]";String result = HttpUtil.post(url, accessToken, param);System.out.println(result);return result;} catch (Exception e) {e.printStackTrace();}return null;}public static void main(String[] args) {Accurate.accurate();}
}

所需要的4个文件具体内容

  • FileUtil
package com.example;import java.io.*;/*** 文件读取工具类*/
public class FileUtil {/*** 读取文件内容,作为字符串返回*/public static String readFileAsString(String filePath) throws IOException {File file = new File(filePath);if (!file.exists()) {throw new FileNotFoundException(filePath);} if (file.length() > 1024 * 1024 * 1024) {throw new IOException("File is too large");} StringBuilder sb = new StringBuilder((int) (file.length()));// 创建字节输入流  FileInputStream fis = new FileInputStream(filePath);  // 创建一个长度为10240的Bufferbyte[] bbuf = new byte[10240];  // 用于保存实际读取的字节数  int hasRead = 0;  while ( (hasRead = fis.read(bbuf)) > 0 ) {  sb.append(new String(bbuf, 0, hasRead));  }  fis.close();  return sb.toString();}/*** 根据文件路径读取byte[] 数组*/public static byte[] readFileByBytes(String filePath) throws IOException {File file = new File(filePath);if (!file.exists()) {throw new FileNotFoundException(filePath);} else {ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());BufferedInputStream in = null;try {in = new BufferedInputStream(new FileInputStream(file));short bufSize = 1024;byte[] buffer = new byte[bufSize];int len1;while (-1 != (len1 = in.read(buffer, 0, bufSize))) {bos.write(buffer, 0, len1);}byte[] var7 = bos.toByteArray();return var7;} finally {try {if (in != null) {in.close();}} catch (IOException var14) {var14.printStackTrace();}bos.close();}}}
}
  • Base64Util 
package com.example;/*** Base64 工具类*/
public class Base64Util {private static final char last2byte = (char) Integer.parseInt("00000011", 2);private static final char last4byte = (char) Integer.parseInt("00001111", 2);private static final char last6byte = (char) Integer.parseInt("00111111", 2);private static final char lead6byte = (char) Integer.parseInt("11111100", 2);private static final char lead4byte = (char) Integer.parseInt("11110000", 2);private static final char lead2byte = (char) Integer.parseInt("11000000", 2);private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};public Base64Util() {}public static String encode(byte[] from) {StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);int num = 0;char currentByte = 0;int i;for (i = 0; i < from.length; ++i) {for (num %= 8; num < 8; num += 6) {switch (num) {case 0:currentByte = (char) (from[i] & lead6byte);currentByte = (char) (currentByte >>> 2);case 1:case 3:case 5:default:break;case 2:currentByte = (char) (from[i] & last6byte);break;case 4:currentByte = (char) (from[i] & last4byte);currentByte = (char) (currentByte << 2);if (i + 1 < from.length) {currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);}break;case 6:currentByte = (char) (from[i] & last2byte);currentByte = (char) (currentByte << 4);if (i + 1 < from.length) {currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);}}to.append(encodeTable[currentByte]);}}if (to.length() % 4 != 0) {for (i = 4 - to.length() % 4; i > 0; --i) {to.append("=");}}return to.toString();}
}
  • HttpUtil 
package com.example;import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;/*** http 工具类*/
public class HttpUtil {public static String post(String requestUrl, String accessToken, String params)throws Exception {String contentType = "application/x-www-form-urlencoded";return HttpUtil.post(requestUrl, accessToken, contentType, params);}public static String post(String requestUrl, String accessToken, String contentType, String params)throws Exception {String encoding = "UTF-8";if (requestUrl.contains("nlp")) {encoding = "GBK";}return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);}public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)throws Exception {String url = requestUrl + "?access_token=" + accessToken;return HttpUtil.postGeneralUrl(url, contentType, params, encoding);}public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)throws Exception {URL url = new URL(generalUrl);// 打开和URL之间的连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("POST");// 设置通用的请求属性connection.setRequestProperty("Content-Type", contentType);connection.setRequestProperty("Connection", "Keep-Alive");connection.setUseCaches(false);connection.setDoOutput(true);connection.setDoInput(true);// 得到请求的输出流对象DataOutputStream out = new DataOutputStream(connection.getOutputStream());out.write(params.getBytes(encoding));out.flush();out.close();// 建立实际的连接connection.connect();// 获取所有响应头字段Map<String, List<String>> headers = connection.getHeaderFields();// 遍历所有的响应头字段for (String key : headers.keySet()) {System.err.println(key + "--->" + headers.get(key));}// 定义 BufferedReader输入流来读取URL的响应BufferedReader in = null;in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));String result = "";String getLine;while ((getLine = in.readLine()) != null) {result += getLine;}in.close();System.err.println("result:" + result);return result;}
}
  • GsonUtils添加会报错,删除不影响最后的结果
  • 整体布局和结果如下图所示

  • 拷贝输出的结果,打开在线Json工具

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/447285.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

做好7步 迅速成为行业专家

行行出状元&#xff0c;但不一定人人能成为行业专家或权威。无论是做独立顾问&#xff0c;还是手下有250名员工的工厂主管&#xff0c;都是在用自己多年丰富经验在帮助企业成功。既然有了专业知识和经验&#xff0c;为什么不把它最大化利用&#xff0c;来建立自己的行业权威&am…

redis常用命令与特性

keys * 返回满足条件的所有key&#xff0c;可以模糊匹配select 数字0-15&#xff0c;进行数据库切换&#xff0c;默认0-15个exists 是否存在指定的keypersist 取消过期时间 select 选择数据库 &#xff08;0-15&#xff0c;总共16个数据库&#xff09;move key index 将当前数据…

紧急不代表重要:管理时间的六个秘密

当整个世界都永远在跟集中精神做事做对的时候&#xff0c;怎么办&#xff1f;Managershare&#xff1a;“世界上效率最高的程序员有什么相同之处&#xff1f;不是经验&#xff0c;薪水或者花在一个项目上的时间&#xff0c;而是他们的老板创造了一个免于走神的环境。”这老板太…

redis安全

定期打补丁禁止一些高危命令 &#xff08;flushdb、keys *、flushall&#xff09;以低权限运行 Redis 服务禁止外网访问 Redis设置访问密码 足够复杂&#xff0c;防止暴力破解 requirepass xxxxxxxx访问权限 内网通过acl限制可以访问redis的ip和端口

如何在三个月内获得三年的工作经验

在多年的工作生涯中&#xff0c;总会目睹一批人的升职像火箭速度一样。 而总有一批人&#xff0c;就像蜗牛一样&#xff0c;工作岗位和职位几乎从来不变。 我们看看&#xff0c;2个名人的快速成长史。 一个是教英语的李阳&#xff0c;他读大学时成绩不好&#xff0c;英语不…

Redis Cluster集群模式

Redis Cluster 它是Redis的分布式解决方案&#xff0c;在Redis 3.0版本正式推出的&#xff0c;有效解决了Redis分布式方面的需求。当遇到单机内存、并发、流量等瓶颈时&#xff0c;可以采用Cluster架构达到负载均衡的目的。数据分布理论: 分布式数据库首要解决把整个数据集按照…

永远和靠谱的人在一起!

巴菲特每年都会同大学生进行座谈&#xff0c;在一次交流会上&#xff0c;有学生问他&#xff1a;您认为一个人最重要的品质是什么?巴菲特没有正面回答这个问题&#xff0c;而是讲了一个小游戏&#xff0c;名为&#xff1a;买进你同学的10%。 巴菲特说&#xff1a;现在给你们一…

Redis事务详解

传统事务的特性 原子性一致性隔离性&#xff1a;事务之间互不干扰持久化&#xff1a;一旦事务提交&#xff0c;无法修改 Redis事务机制 MULTI、EXEC、DISCARD和WATCH命令是Redis事务功能的基础。Redis事务允许在一次单独的步骤中执行一组命令&#xff0c;并且可以保证如下两个…

工作的最终目的

当时公司招了大批应届本科和研究生毕业的新新人类。平均年龄25岁。那个新的助理&#xff0c;是经过多次面试后&#xff0c;我亲自招回来的一个女孩。名牌大学本科毕业&#xff0c;聪明&#xff0c;性格活泼。私下里我得承认&#xff0c;我招她的一个很重要的原因&#xff0c;除…

销售员所做的一切工作最终目的就是为了成交

&#xff08;1&#xff09;最后一次报价禁忌.报价过晚或者过于匆忙步幅度太大&#xff0c;显得过于慷慨;让步幅度太小&#xff0c;显得毫无意义当谈判进展到最后&#xff0c;双方只是在最后的某一两个问题上尚有不同意见&#xff0c;过让步才能求得一致&#xff0c;签订协议。在…

Redis java客户端操作

jedis jedis官方指定的redis java客户端&#xff0c;将其导入到pom.xml问价内 <!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><vers…

HEVC/H265 namespace 介绍

在 HEVC/H265 代码中&#xff0c;有三个使用的namespace&#xff1a; 1. df 2. df::program_options_lite 3. RasterAddress 对于第一个 df 的namespace&#xff0c;我一直百思不得其解&#xff0c;df 是什么含义&#xff1f;老外对起名是很重视的&#xff0c;肯定有原因。…

Redis整合Springboot实现数据共享

代码的整体结构 RedisSessionConfig.java package com.cc.springbootredissession.config;import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;Configuration E…

人生什么最重要

什么最重要 20岁的人说,学习成绩最重要.一次考试分数,可以把人分为三六九等.&#xff02;博士&#xff02;,&#xff02;本科&#xff02;,&#xff02;大专&#xff02;&#xff02;高职&#xff02;&#xff02;中专&#xff02;,成绩好的上好学校,成绩差的上差学校;成绩好的…

Redis整合Springboot实现单机配置

整体结构 配置文件 <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation"http://maven.apache.org/…

撑起整个互联网的7大开源技术

撑起整个互联网的7大开源技术 很多人可能尚未意识到&#xff0c;我们使用的电脑中运行有开源软件&#xff0c;手机中运行有开源软件&#xff0c;家里的电视也运行有开源软件&#xff0c;甚至小小的数码产品中也运行有开源软件&#xff0c;尤其是互联网服务器端软件&#xff0c…

Redis整合springboot实现哨兵模式

整体结构 RedisConfig package com.cc.springredis.config;import com.cc.springredis.RedisUtil; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.R…

Redis整合springboot实现集群模式

整体结构 Redis.config package com.cc.springredis.config;import com.cc.springredis.RedisUtil; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection…

一个穷人是从什么时候开始有钱的?

2010年&#xff0c;文野31岁那年&#xff0c;买房后第二年&#xff0c;完成了「人生中最重要的一次转变」。 这一年&#xff0c;他在心里对自己的定位&#xff0c;从穷人变成了有钱人。 「一些人哪怕有钱了&#xff0c;心里也永远甩不脱穷的影子。」这是我曾经在《 阶段性胜…

Redis整合springboot实现消息队列

publisher消息的发出 代码整体的结构 publisherConfig package com.cc.springbootredispublisher.config;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.conne…