Java代码实现获取百度智能云access_token

本文介绍如何通过Java代码调用BaiduAI的OAuth2.0接口获取access_token,以及常见问题和解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

场景:业务需要获取到access_token,然后去看了文档,并根据文档上的代码示例调用不成功

 https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu

使用以下代码示例能够轻松获取,只需要将clientId和clientSecret换成自己的apikey和secretkey就可以了。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class AccessToken{
   public static void main(String[] args) {
        String accessToken = getAccessToken();
        System.out.println("Access Token: " + accessToken);
    }

    private static String getAccessToken() {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        StringBuilder response = new StringBuilder();
        try {
            String url = "https://aip.baidubce.com/oauth/2.0/token";
            String grantType = "client_credentials";
            String clientId = "11111111111111";
            String clientSecret = "22222222222222222";
            String apiUrl = String.format("%s?grant_type=%s&client_id=%s&client_secret=%s",
                    url, grantType, clientId, clientSecret);

            URL apiURL = new URL(apiUrl);
            connection = (HttpURLConnection) apiURL.openConnection();
            connection.setRequestMethod("POST");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            } else {
                System.out.println("Error response code: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //取出返回的access_token
        JSONObject jsonObject = JSON.parseObject(response.toString());
        String accessToken = jsonObject.getString("access_token");
        return accessToken;
    }
}

### Java 集成百度智能云语音识别服务 为了在Java项目中集成百度智能云的语音识别服务,开发者需遵循一系列特定步骤来配置环境并编写相应的代码。这不仅涉及设置必要的开发工具链,还包括理解如何通过API调用来实现语音文件向文本数据转换的功能。 #### 准备工作 首先,在开始编码之前,确保已注册成为百度AI平台用户,并获取到应用对应的`API Key`和`Secret Key`用于身份验证[^1]。接着,创建一个新的Maven工程作为项目的起点;在此过程中,记得引入JSON处理库以便于解析返回的数据结构: ```xml <dependencies> <!-- JSONObject --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20210307</version> </dependency> </dependencies> ``` 此部分操作对于后续能够顺利发送请求至服务器至关重要[^4]。 #### 编写核心逻辑 当准备工作完成后,可以着手构建实际执行语音识别的核心功能模块。下面给出了一段简化版的例子,展示了怎样利用HTTP POST方法上传音频流给定接口地址完成一次完整的交互过程: ```java // 导入所需包 import java.io.*; import javax.net.ssl.HttpsURLConnection; import org.json.JSONObject; public class BaiduSpeechRecognition { private static final String API_KEY = "your_api_key"; private static final String SECRET_KEY = "your_secret_key"; public static void main(String[] args) throws Exception { // 获取token String accessTokenUrl = "https://aip.baidubce.com/oauth/2.0/token" + "?grant_type=client_credentials" + "&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY; URL url = new URL(accessTokenUrl); HttpsURLConnection connection = (HttpsURLConnection)url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder responseBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null){ responseBuilder.append(line); } JSONObject jsonResponse = new JSONObject(responseBuilder.toString()); String token = jsonResponse.getString("access_token"); // 发送语音识别请求 String recognitionApiUrl = "https://vop.baidu.com/server_api?cuid=xxxxxx&token="+token; File audioFile = new File("/path/to/audio/file.pcm"); byte[] fileContent = Files.readAllBytes(audioFile.toPath()); connection.setRequestMethod("POST"); connection.setDoOutput(true); try (OutputStream os = connection.getOutputStream()){ os.write(fileContent); } System.out.println("conn.getResponseCode() = " + connection.getResponseCode()); InputStream inputStream = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; StringBuffer content = new StringBuffer(); while ((inputLine = bufferedReader.readLine()) != null) { content.append(inputLine); } bufferedReader.close(); System.out.println(content.toString()); } } ``` 上述程序片段实现了两个主要目标:一是通过OAuth机制获得访问令牌;二是运用该令牌发起针对指定路径下PCM格式音频文件的识别请求,并打印最终得到的结果字符串[^2]。 值得注意的是,这里假设输入源已经过预处理转化为适合传输的标准形式——即线性采样率16kHz、单声道且无压缩编码的原始声音信号(通常保存为`.pcm`扩展名)。如果待分析材料并非如此,则可能还需要额外加入一段转换流程以满足接收端的要求[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值