package com.fuyuanshen.app.http; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; /** * 获取阿里云TTS服务访问令牌 */ public class TokenClient { public static String getAccessToken(String accessKeyId, String accessKeySecret) throws IOException { String endpoint = "https://nls-meta.cn-shanghai.aliyuncs.com/v1/token"; URL url = new URL(endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); // 发送认证信息 String params = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s", accessKeyId, accessKeySecret); try (OutputStream os = conn.getOutputStream()) { os.write(params.getBytes("UTF-8")); } int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { try (InputStream is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } // 解析响应获取token(实际需要使用JSON解析库) return response.toString().replaceAll(".*\"access_token\":\"([^\"]+)\".*", "$1"); } } else { throw new IOException("获取令牌失败,状态码: " + responseCode); } } }