一个基于 Spring Boot 的实现,用于代理百度 AI 的 OCR 接口

一个基于 Spring Boot 的实现,用于代理百度 AI 的 OCR 接口

    • BaiduAIController.java
    • BaiduAIConfig.java
    • [在 application.yml 或 application.properties 中添加配置:application.yml](#在 application.yml 或 application.properties 中添加配置:application.yml)
    • [同时,需要在Spring Boot应用中配置RestTemplate:ApplicationConfig.java](#同时,需要在Spring Boot应用中配置RestTemplate:ApplicationConfig.java)

BaiduAIController.java

java 复制代码
package com.ranfeng.controller;

import com.ranfeng.common.core.domain.AjaxResult;
import com.ranfeng.config.BaiduAIConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 百度AI接口代理控制器
 */
@RestController
@RequestMapping("/api/baidu")
public class BaiduAIController {

    @Autowired
    private BaiduAIConfig baiduAIConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取百度AI的access token
     */
    @GetMapping("/token")
    public AjaxResult getToken() {
        try {
            String url = "https://aip.baidubce.com/oauth/2.0/token";
            
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("grant_type", "client_credentials");
            params.add("client_id", baiduAIConfig.getApiKey());
            params.add("client_secret", baiduAIConfig.getSecretKey());
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            
            Map<String, Object> response = restTemplate.postForObject(url, requestEntity, Map.class);
            
            return AjaxResult.success(response);
        } catch (Exception e) {
            return AjaxResult.error("获取百度AI Token失败: " + e.getMessage());
        }
    }

    /**
     * 调用百度OCR识别接口
     */
    @PostMapping("/ocr")
    public AjaxResult ocrRecognize(@RequestBody Map<String, Object> requestData) {
        try {
            // 获取token
            String tokenUrl = "https://aip.baidubce.com/oauth/2.0/token";
            
            MultiValueMap<String, String> tokenParams = new LinkedMultiValueMap<>();
            tokenParams.add("grant_type", "client_credentials");
            tokenParams.add("client_id", baiduAIConfig.getApiKey());
            tokenParams.add("client_secret", baiduAIConfig.getSecretKey());
            
            HttpHeaders tokenHeaders = new HttpHeaders();
            tokenHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            
            HttpEntity<MultiValueMap<String, String>> tokenRequestEntity = new HttpEntity<>(tokenParams, tokenHeaders);
            
            Map<String, Object> tokenResponse = restTemplate.postForObject(tokenUrl, tokenRequestEntity, Map.class);
            String accessToken = (String) tokenResponse.get("access_token");
            
            // 调用OCR接口
            String ocrUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + accessToken;
            
            MultiValueMap<String, String> ocrParams = new LinkedMultiValueMap<>();
            ocrParams.add("image", (String) requestData.get("image"));
            ocrParams.add("language_type", (String) requestData.get("language_type"));
            ocrParams.add("detect_direction", (String) requestData.get("detect_direction"));
            ocrParams.add("probability", (String) requestData.get("probability"));
            
            HttpHeaders ocrHeaders = new HttpHeaders();
            ocrHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            
            HttpEntity<MultiValueMap<String, String>> ocrRequestEntity = new HttpEntity<>(ocrParams, ocrHeaders);
            
            Map<String, Object> ocrResponse = restTemplate.postForObject(ocrUrl, ocrRequestEntity, Map.class);
            
            return AjaxResult.success(ocrResponse);
        } catch (Exception e) {
            return AjaxResult.error("OCR识别失败: " + e.getMessage());
        }
    }
}

BaiduAIConfig.java

java 复制代码
package com.ranfeng.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * 百度AI配置类
 */
@Configuration
@ConfigurationProperties(prefix = "baidu.ai")
public class BaiduAIConfig {
    
    private String apiKey;
    private String secretKey;
    
    public String getApiKey() {
        return apiKey;
    }
    
    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }
    
    public String getSecretKey() {
        return secretKey;
    }
    
    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }
}

在 application.yml 或 application.properties 中添加配置:application.yml

yaml 复制代码
# 百度AI配置
baidu:
  ai:
    api-key: xxxxx
    secret-key: xxxxxx

同时,需要在Spring Boot应用中配置RestTemplate:ApplicationConfig.java

java 复制代码
package com.ranfeng.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ApplicationConfig {
    
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
相关推荐
CodeJourney.几秒前
ChemBlender:科研绘图创新解决方案
数据库·人工智能·信息可视化·excel
电鱼智能的电小鱼4 分钟前
产线视觉检测设备技术方案:基于EFISH-SCB-RK3588/SAIL-RK3588的国产化替代赛扬N100/N150全场景技术解析
linux·人工智能·嵌入式硬件·计算机视觉·视觉检测·实时音视频
妄想成为master10 分钟前
计算机视觉----基于锚点的车道线检测、从Line-CNN到CLRNet到CLRKDNet 本文所提算法Line-CNN 后续会更新以下全部算法
人工智能·计算机视觉·车道线检测
夜幕龙20 分钟前
LeRobot 项目部署运行逻辑(七)—— ACT 在 Mobile ALOHA 训练与部署
人工智能·深度学习·机器学习
未来之窗软件服务44 分钟前
人体肢体渲染-一步几个脚印从头设计数字生命——仙盟创梦IDE
开发语言·ide·人工智能·python·pygame·仙盟创梦ide
Echo``1 小时前
40:相机与镜头选型
开发语言·人工智能·深度学习·计算机视觉·视觉检测
Christo31 小时前
关于在深度聚类中Representation Collapse现象
人工智能·深度学习·算法·机器学习·数据挖掘·embedding·聚类
Apache RocketMQ1 小时前
Apache RocketMQ ACL 2.0 全新升级
人工智能
QX_hao1 小时前
【project】--数据挖掘
人工智能·数据挖掘
showmethetime1 小时前
matlab提取脑电数据的五种频域特征指标数值
前端·人工智能·matlab