告别复杂配置!Spring Boot优雅集成百度OCR的终极方案

1. 准备工作

1.1 注册百度AI开放平台
  1. 访问百度AI开放平台

  2. 注册账号并登录

  3. 进入控制台 → 文字识别 → 创建应用

  4. 记录下API KeySecret Key


2. 项目配置

2.1 添加依赖 (pom.xml)
XML 复制代码
<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- Configuration Properties 处理器 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    
    <!-- Apache HttpClient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
    </dependency>
    
    <!-- JSON 处理 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
</dependencies>
2.2 配置YAML (application.yml)
TypeScript 复制代码
baidu:
  ocr:
    api-key: "your_api_key"         # 替换为你的API Key
    secret-key: "your_secret_key"   # 替换为你的Secret Key
    access-token-url: "https://aip.baidubce.com/oauth/2.0/token"
    general-basic-url: "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"

3. 配置参数封装

3.1 创建配置类 (BaiduOcrProperties.java)
TypeScript 复制代码
@Data
@Builder
@Component
@AllArgsConstructor
@NoArgsConstructor
@ConfigurationProperties(prefix = "baidu.ocr")
public class BaiduOcrProperties {
    private String apiKey;
    private String secretKey;
    private String accessTokenUrl;
    private String generalBasicUrl;
}

4. OCR服务实现

4.1 工具类:获取Access Token (AccessTokenUtil.java)
TypeScript 复制代码
@Component
public class AccessTokenUtil {

    private final BaiduOcrProperties ocrProperties;

    @Autowired
    public AccessTokenUtil(BaiduOcrProperties ocrProperties) {
        this.ocrProperties = ocrProperties;
    }

    public String getAccessToken() throws IOException {
        String url = String.format("%s?grant_type=client_credentials&client_id=%s&client_secret=%s",
                ocrProperties.getAccessTokenUrl(),
                ocrProperties.getApiKey(),
                ocrProperties.getSecretKey());

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                String json = EntityUtils.toString(entity);
                // 解析JSON获取access_token
                return json.split("\"access_token\":\"")[1].split("\"")[0];
            }
        }
    }
}
4.2 OCR服务类 (BaiduOcrService.java)
TypeScript 复制代码
@Service
public class BaiduOcrService {

    private final AccessTokenUtil accessTokenUtil;
    private final BaiduOcrProperties ocrProperties;

    @Autowired
    public BaiduOcrService(AccessTokenUtil accessTokenUtil, BaiduOcrProperties ocrProperties) {
        this.accessTokenUtil = accessTokenUtil;
        this.ocrProperties = ocrProperties;
    }

    public String recognizeText(MultipartFile file) throws IOException {
        // 1. 获取Access Token
        String accessToken = accessTokenUtil.getAccessToken();

        // 2. 将图片转换为Base64
        String imageBase64 = Base64.getEncoder().encodeToString(file.getBytes());

        // 3. 构建请求参数
        Map<String, String> params = new HashMap<>();
        params.put("image", imageBase64);
        params.put("language_type", "CHN_ENG"); // 中英文混合

        // 4. 发送OCR请求
        String url = ocrProperties.getGeneralBasicUrl() + "?access_token=" + accessToken;
        return postFormData(url, params);
    }

    private String postFormData(String url, Map<String, String> params) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            // 构建表单参数
            StringBuilder formData = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (!formData.isEmpty()) formData.append("&");
                formData.append(entry.getKey()).append("=").append(entry.getValue());
            }

            httpPost.setEntity(new StringEntity(formData.toString()));

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity);
            }
        }
    }
}

5. 控制器层

5.1 图片识别接口 (OcrController.java)
TypeScript 复制代码
@RestController
public class OcrController {

    private final BaiduOcrService ocrService;

    @Autowired
    public OcrController(BaiduOcrService ocrService) {
        this.ocrService = ocrService;
    }

    @PostMapping("/ocr")
    public String recognizeImage(@RequestParam("image") MultipartFile file) {
        try {
            return ocrService.recognizeText(file);
        } catch (Exception e) {
            return "{\"error\": \"" + e.getMessage() + "\"}";
        }
    }
}

6. 关键点说明

  1. 配置封装

    使用@ConfigurationProperties将YAML中的配置自动绑定到Java对象

  2. Access Token获取

    百度OCR需要先获取临时Access Token(有效期30天)

  3. 图片处理

    将上传的图片转换为Base64编码

  4. 错误处理

    实际生产中需添加更完善的异常处理机制

  5. 性能优化

    • 缓存Access Token(避免每次请求都获取)

    • 使用连接池管理HTTP客户端

    • 限制上传图片大小(在application.yml中配置spring.servlet.multipart.max-file-size


完整项目结构

复制代码
src/main/java
├── com/example/demo
│   ├── config
│   │   └── BaiduOcrProperties.java
│   ├── controller
│   │   └── OcrController.java
│   ├── service
│   │   ├── BaiduOcrService.java
│   │   └── AccessTokenUtil.java
│   └── DemoApplication.java
resources
└── application.yml

通过以上步骤,你已完成了一个可扩展的Spring Boot百度OCR集成方案。实际部署时请将YAML中的API密钥替换为你的实际密钥。

相关推荐
向葭奔赴♡1 小时前
Spring Boot 分模块:从数据库到前端接口
数据库·spring boot·后端
计算机毕业设计木哥1 小时前
计算机毕业设计选题推荐:基于SpringBoot和Vue的爱心公益网站
java·开发语言·vue.js·spring boot·后端·课程设计
番茄Salad1 小时前
自定义Spring Boot Starter项目并且在其他项目中通过pom引入使用
java·spring boot
熊猫钓鱼>_>2 小时前
AI驱动的专业报告撰写:从信息整合到洞察生成的全新范式
大数据·人工智能·百度
MC丶科8 小时前
【SpringBoot 快速上手实战系列】5 分钟用 Spring Boot 搭建一个用户管理系统(含前后端分离)!新手也能一次跑通!
java·vue.js·spring boot·后端
lang2015092810 小时前
Spring Boot 入门:5分钟搭建Hello World
java·spring boot·后端
Javashop_jjj11 小时前
三勾软件| 用SpringBoot+Element-UI+UniApp+Redis+MySQL打造的点餐连锁系统
spring boot·ui·uni-app
PHP源码12 小时前
SpringBoot校园二手商城系统
java·spring boot·springboot二手商城·java校园二手商城系统
毕业设计制作和分享12 小时前
springboot159基于springboot框架开发的景区民宿预约系统的设计与实现
java·spring boot·后端