将你提供的 TypeScript 代码转换为 Java 代码的一个常见方法是使用 HttpURLConnection 或第三方库如 OkHttp 或 Apache HttpClient 来处理 HTTP 请求。以下示例使用 OkHttp 库来实现与原始 TypeScript 代码等效的功能。
首先,确保在你的 Maven pom.xml 文件中添加了 OkHttp 的依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.2</version> <!-- 使用最新版本 -->
</dependency>
然后,可以使用以下 Java 代码来实现相应的功能:
import okhttp3.*;
import java.io.File;
import java.io.IOException;
public class AiTranscriptions {
public static String aiTranscriptions(String model, File file) throws IOException {
// 创建 OkHttpClient 实例
OkHttpClient client = new OkHttpClient();
// 创建请求体
MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("model", model)
.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("audio/mpeg"), file)); // 根据文件类型修改 MediaType
// 获取 Axios 配置
String baseUrl = getBaseUrl(); // 实现获得 baseUrl 的方法
String authorization = getAuthorization(); // 实现获得授权的方式
// 创建请求
Request request = new Request.Builder()
.url(baseUrl + "/audio/transcriptions")
.post(requestBodyBuilder.build())
.addHeader("Authorization", authorization)
.build();
// 发送请求并获取响应
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// 解析响应体
String responseBody = response.body().string();
return responseBody; // 返回服务器返回的内容
}
}
private static String getBaseUrl() {
// 实现获取基 URL 的逻辑
return "https://api.example.com"; // 例子
}
private static String getAuthorization() {
// 实现获取授权 token 的逻辑
return "Bearer your_token"; // 例子
}
public static void main(String[] args) {
try {
File file = new File("path/to/your/audio/file.mp3"); // 替换为你的文件路径
String model = "your_model"; // 替换为你的模型
String result = aiTranscriptions(model, file);
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
代码解释:
- File:使用
File 类来表示将要上传的音频文件。
- OkHttpClient:用于发送网络请求的类。
- MultipartBody:用于构造 multipart/form-data 请求体,使我们可以发送文件和其他数据。
- Request:构建 HTTP 请求,包括 URL 和请求方法。
- Response:处理服务器返回的响应。
请根据你的具体应用需求和项目结构,调整 getBaseUrl() 和 getAuthorization() 方法的实现。
要从 Vue 前端发送文件流到 Java 后端,我们需要首先确保在 Vue 前端正确地使用 FormData 对象,上传文件,然后在 Java 后端处理上传的文件。以下是改变后的 Vue 前端代码和与之对应的 Java 后端代码。
Vue 前端代码
以下是一个示例 Vue 组件,它允许用户选择音频文件并将其上传到后端:
<template>
<div>
<input type="file" @change="onFileChange" accept="audio/*" />
<button @click="uploadFile">Upload</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
selectedFile: null,
model: 'your_model', // 替换为你的模型
};
},
methods: {
onFileChange(event) {
this.selectedFile = event.target.files[0];
},
async uploadFile() {
if (!this.selectedFile) {
alert("Please select a file first!");
return;
}
const formData = new FormData();
formData.append('model', this.model);
formData.append('file', this.selectedFile);
try {
const response = await axios.post('https://api.example.com/audio/transcriptions', formData, {
headers: {
'Content-Type': 'multipart/form-data',
// 需要在这里添加 Authorization 头
'Authorization': 'Bearer your_token', // 替换为你的 token
},
});
console.log(response.data);
} catch (error) {
console.error("Error uploading file:", error);
}
},
},
};
</script>
Java 后端代码
Java 后端代码的处理逻辑保持不变,目标是正确接收前端发送的文件流。你可以使用 Spring Boot(假设你在使用 Spring Boot)来处理文件上传:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/audio")
public class AudioController {
@PostMapping("/transcriptions")
public ResponseEntity<String> aiTranscriptions(
@RequestParam("model") String model,
@RequestParam("file") MultipartFile file) {
// 处理上传的音频文件
if (file.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File is empty");
}
// 这里可以添加逻辑处理音频文件
// 例如,保存文件、调用 AI 转写服务等
// 假设处理完成后返回的结果
String result = "Transcription result for model " + model;
return ResponseEntity.ok(result);
}
}
注意事项:
- 文件接收:在 Java 后端中,
@RequestParam 注解用于接收前端发送的文件。
- CORS: 确保后端服务器允许来自前端的 CORS 请求。如果前端和后端不在同一域下,可能会遇到跨域请求问题,需在后端添加 CORS 配置。
- Authorization: 在 Vue 前端发送请求时,确保用适当的 token 更新
Authorization 的值。
- 文件类型: 可以在前端通过
accept="audio/*" 属性限制文件选择,确保只选取音频文件。
通过这种方式,您可以从 Vue 前端向 Java 后端发送音频文件流,后端会正确接收并处理文件。
在后端处理文件上传并调用 Whisper API 以获取转换文本的实现需要进行以下步骤:
- 接收音频文件。
- 将文件发送到 Whisper API。
- 处理 Whisper API 的响应并返回转换后的文本。
以下是一个完整的示例,展示如何在 Java 后端中实现这些步骤。我们继续使用 Spring Boot 作为后端框架,并且假设您已经添加了 rest-template 或 okhttp 来发送 HTTP 请求。
1. 添加依赖
假设我们使用 RestTemplate 来调用 Whisper API。确保在 pom.xml 文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. Java 后端代码
下面的 Java 代码实现了上传文件后与 Whisper API 通信的逻辑。
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.HttpClientErrorException;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/audio")
public class AudioController {
private final RestTemplate restTemplate;
public AudioController(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@PostMapping("/transcriptions")
public ResponseEntity<String> aiTranscriptions(
@RequestParam("model") String model,
@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("File is empty");
}
String whisperApiUrl = "https://api.whisper.com/v1/transcriptions"; // Whisper API 的 URL
String authorizationToken = "Bearer your_whisper_token"; // Whisper API 的 Token,替换为实际 token
// 封装请求头
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", authorizationToken);
headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);
// 封装请求体
MultiValueMap<String, Object> body = new org.springframework.util.LinkedMultiValueMap<>();
body.add("model", model);
// 这里添加文件流,使用 MultipartFile 的 getResource() 方法获取文件输入流
body.add("file", new org.springframework.core.io.InputStreamResource(file.getInputStream()));
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
try {
// 调用 Whisper API
ResponseEntity<Map> response = restTemplate.exchange(
whisperApiUrl,
HttpMethod.POST,
requestEntity,
Map.class
);
// 获取转换的文本
String transcribedText = (String) response.getBody().get("text");
return ResponseEntity.ok(transcribedText); // 返回转换后的文本
} catch (HttpClientErrorException e) {
return ResponseEntity.status(e.getStatusCode()).body("Error calling Whisper API: " + e.getResponseBodyAsString());
} catch (Exception e) {
return ResponseEntity.status(500).body("Internal server error: " + e.getMessage());
}
}
}
3. 代码解释
-
请求头: HttpHeaders 中设置了 Authorization 头部以便将 token 发送到 Whisper API。
-
请求体: 使用 MultiValueMap 来构造请求体, 包含模型名和文件流。InputStreamResource 用于将 MultipartFile 转换为输入流。
-
调用 Whisper API: 使用 RestTemplate 的 exchange 方法发送 POST 请求,并处理响应。
-
处理错误: 针对常见错误进行了异常处理,返回相应的错误信息。
4. 注意事项
- 根据实际情况替换
whisperApiUrl 和 authorizationToken。
- 在生产环境中,请确保对敏感信息(如 API Token)进行适当的保密处理。
- 您可能需要根据 Whisper API 的实际响应格式,调整解析方法,以确保能正确获取到转换后的文本。
- 为了运行
RestTemplate,确保在 @SpringBootApplication 主类中使用 @EnableAutoConfiguration 或配置 Bean。
通过这些步骤,可以实现将音频文件上传到您的后端,并调用 Whisper API 进行文本转换的功能。
若要使用 HttpPost 进行请求,可以使用 Apache HttpClient 库。以下示范展示了如何接收音频文件,并使用 HttpPost 向 Whisper API 发送请求,以获取转换的文本。
首先,您需要确保在 pom.xml 中添加 Apache HttpClient 的依赖:
添加依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version> <!-- 使用最新版本 -->
</dependency>
修改后的 Java 后端代码
以下是使用 HttpPost 的实现:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@RestController
@RequestMapping("/audio")
public class AudioController {
@PostMapping("/transcriptions")
public ResponseEntity<String> aiTranscriptions(
@RequestParam("model") String model,
@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("File is empty");
}
String whisperApiUrl = "https://api.whisper.com/v1/transcriptions"; // Whisper API 的 URL
String authorizationToken = "Bearer your_whisper_token"; // Whisper API 的 Token,替换为实际 token
// 创建 CloseableHttpClient
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建 HttpPost 请求
HttpPost httpPost = new HttpPost(whisperApiUrl);
httpPost.setHeader("Authorization", authorizationToken);
// 创建 MultipartEntityBuilder
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("model", model);
builder.addBinaryBody("file", file.getInputStream(), ContentType.APPLICATION_OCTET_STREAM, file.getOriginalFilename());
// 设置请求实体
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
// 执行请求,并获取响应
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
// 处理响应
if (responseEntity != null) {
String responseBody = EntityUtils.toString(responseEntity);
// 假设响应是 JSON 格式并且包含 "text" 字段
// 根据实际情况修改解析方案
return ResponseEntity.ok(responseBody);
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("No response from Whisper API");
}
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error calling Whisper API: " + e.getMessage());
}
}
}
代码解释
-
引入 HttpClient: 使用 Apache HttpClient 创建 HTTP 请求,并处理响应。
-
HttpPost 请求: 创建 HttpPost 对象,设置目标 URL 和 Authorization 头部。
-
MultipartEntityBuilder: 用于构造 multipart 请求体,方便发送文件和其他文本字段。
-
执行请求: 使用 CloseableHttpClient 执行请求并获取响应。对服务器返回的数据进行处理。
-
异常处理: 捕获可能的 IO 异常,返回相应的错误消息。
注意事项
- 确保根据 Whisper API 的响应格式解析并提取所需文本。
- 此示例用于简单的例子实践。在生产环境中,一定要考虑更多的错误处理和日志记录机制。
- 您可能还需要在
@RestController 类中确保对异常进行适当的处理,例如使用 @ExceptionHandler 来处理全局异常。
为了从 Whisper API 的响应中提取 "text" 字段并将其返回,可以使用一个 JSON 处理库,如 Jackson 或 Gson。在这里,我将使用 Jackson,因为 Spring Boot 默认集成了它。
首先,确保在 pom.xml 中包含 Jackson 的依赖,但通常 Spring Boot 项目已经包含,如果没有,请确保添加如下依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
然后,您需要创建一个 Java 类来表示 Whisper API 的响应结构。在这里,我们只需要一个 text 字段。
1. 创建 WhisperResponse 类
import com.fasterxml.jackson.annotation.JsonProperty;
public class WhisperResponse {
@JsonProperty("text")
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
2. 修改 AudioController 以解析响应
以下是完整的 AudioController 实现,其中包含从 Whisper API 响应中提取文本的逻辑:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@RestController
@RequestMapping("/audio")
public class AudioController {
@PostMapping("/transcriptions")
public ResponseEntity<String> aiTranscriptions(
@RequestParam("model") String model,
@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("File is empty");
}
String whisperApiUrl = "https://api.whisper.com/v1/transcriptions"; // Whisper API 的 URL
String authorizationToken = "Bearer your_whisper_token"; // Whisper API 的 Token
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(whisperApiUrl);
httpPost.setHeader("Authorization", authorizationToken);
// 构建 multipart 请求
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("model", model);
builder.addBinaryBody("file", file.getInputStream(), ContentType.APPLICATION_OCTET_STREAM, file.getOriginalFilename());
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
// 执行请求并获取响应
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
String responseBody = EntityUtils.toString(responseEntity);
// 使用 Jackson 解析 JSON 响应
ObjectMapper mapper = new ObjectMapper();
WhisperResponse whisperResponse = mapper.readValue(responseBody, WhisperResponse.class);
if (whisperResponse.getText() != null) {
return ResponseEntity.ok(whisperResponse.getText()); // 返回转换后的文本
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Text field is missing in the Whisper API response.");
}
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("No response from Whisper API");
}
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error calling Whisper API: " + e.getMessage());
}
}
}
代码解释
-
WhisperResponse 类: 该类用于映射 Whisper API 响应中的 JSON 格式。@JsonProperty 注解用于让 Jackson 知道要映射的 JSON 字段名。
-
ObjectMapper: 使用 Jackson 的 ObjectMapper 来将响应的 JSON 字符串转换为 WhisperResponse 对象。
-
解析文本: 从 whisperResponse 对象中提取 text 字段,并将其返回。如果 text 字段缺失,则返回适当的错误消息。
-
异常处理: 捕获 IO 异常,返回清晰的错误消息,以便于调试。
注意事项
- 确保 Whisper API 的 URL 以及 Token 是正确的。
- 在实际应用中,您可能还需要对返回的 JSON 结构进行更多的解析,具体取决于 API 的实际响应,这里我们假设只包含
text 字段。