一个基于 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();
    }
}
相关推荐
Mountain and sea3 小时前
从零搭建工业机器人激光切割+焊接产线:KUKA七轴协同+节卡AGV+视觉检测实战复盘
人工智能·机器人·视觉检测
K姐研究社3 小时前
阿里JVS Claw实测 – 手机一键部署 OpenClaw,开箱即用
人工智能·智能手机·aigc·飞书
卷积殉铁子3 小时前
从“手动挡”到“自动驾驶”:OpenClaw如何让AI开发变成“说话就行”
人工智能
机器之心4 小时前
扎克伯格正在打造自己的「AI分身」,并计划裁掉1.6万人
人工智能·openai
机器之心4 小时前
必看!Sebastian Raschka新博客盘点了所有主要注意力机制
人工智能·openai
彭于晏Yan4 小时前
Spring AI(二):入门使用
java·spring boot·spring·ai
Kel4 小时前
深入剖析 openai-node 源码:一个工业级 TypeScript SDK 的架构之美
javascript·人工智能·架构
岛雨QA5 小时前
Skill学习指南🧑‍💻
人工智能·agent·ai编程
波动几何5 小时前
从人性到无名:一条向内的觉悟之路
人工智能
EllenLiu5 小时前
架构演进与性能压榨:在金融 RAG 中引入条款森林 (FoC)
人工智能·架构