一个基于 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();
    }
}
相关推荐
白-胖-子28 分钟前
深入剖析大模型在文本生成式 AI 产品架构中的核心地位
人工智能·架构
想要成为计算机高手2 小时前
11. isaacsim4.2教程-Transform 树与Odometry
人工智能·机器人·自动驾驶·ros·rviz·isaac sim·仿真环境
静心问道2 小时前
InstructBLIP:通过指令微调迈向通用视觉-语言模型
人工智能·多模态·ai技术应用
宇称不守恒4.03 小时前
2025暑期—06神经网络-常见网络2
网络·人工智能·神经网络
小楓12013 小时前
醫護行業在未來會被AI淘汰嗎?
人工智能·醫療·護理·職業
数据与人工智能律师3 小时前
数字迷雾中的安全锚点:解码匿名化与假名化的法律边界与商业价值
大数据·网络·人工智能·云计算·区块链
chenchihwen3 小时前
大模型应用班-第2课 DeepSeek使用与提示词工程课程重点 学习ollama 安装 用deepseek-r1:1.5b 分析PDF 内容
人工智能·学习
说私域4 小时前
公域流量向私域流量转化策略研究——基于开源AI智能客服、AI智能名片与S2B2C商城小程序的融合应用
人工智能·小程序
Java樱木4 小时前
AI 编程工具 Trae 重要的升级。。。
人工智能
凪卄12134 小时前
图像预处理 二
人工智能·python·深度学习·计算机视觉·pycharm