完整使用样例

以下示例展示完整的"创建任务 → 轮询状态 → 获取结果"流程。

curl

#!/bin/bash
BASE="http://127.0.0.1:9527"
KEY="dk_your_api_key_here"

# 1. 创建任务
RESP=$(curl -s -X POST "$BASE/api/dev/tasks" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $KEY" \
  -d '{"title":"测试","videoPath":"/path/to/video.mp4","sourceLanguage":"en","targetLanguage":"zh"}')
TASK_ID=$(echo "$RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['taskId'])")
echo "任务 ID: $TASK_ID"

# 2. 轮询状态
while true; do
  STATUS=$(curl -s "$BASE/api/dev/tasks/$TASK_ID/status" -H "X-API-Key: $KEY")
  STATE=$(echo "$STATUS" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['status'])")
  echo "  状态: $STATE"
  [ "$STATE" = "completed" ] || [ "$STATE" = "failed" ] && break
  sleep 3
done

# 3. 获取结果
curl -s "$BASE/api/dev/tasks/$TASK_ID/export" -H "X-API-Key: $KEY"

Python

import requests, time, sys

BASE = "http://127.0.0.1:9527"
HEADERS = {"X-API-Key": "dk_your_api_key_here"}

# 创建任务
resp = requests.post(f"{BASE}/api/dev/tasks", headers={**HEADERS, "Content-Type": "application/json"}, json={
    "title": "翻译任务", "videoPath": "/path/to/video.mp4",
    "sourceLanguage": "en", "targetLanguage": "zh"
})
data = resp.json()
if not data.get("ok"):
    print(f"创建失败: {data.get('error')}")
    sys.exit(1)
task_id = data["data"]["taskId"]
print(f"任务 ID: {task_id}")

# 轮询状态
while True:
    r = requests.get(f"{BASE}/api/dev/tasks/{task_id}/status", headers=HEADERS)
    d = r.json()["data"]
    print(f"  状态: {d['status']}  进度: {d['progress']}%")
    if d["status"] in ("completed", "failed"):
        break
    time.sleep(3)

# 获取结果
if d["status"] == "completed":
    r = requests.get(f"{BASE}/api/dev/tasks/{task_id}/export", headers=HEADERS)
    print(f"导出路径: {r.json()['data']['exportPath']}")

Node.js

const BASE = 'http://127.0.0.1:9527'
const KEY = 'dk_your_api_key_here'

async function request(method, path, body) {
  const resp = await fetch(BASE + path, {
    method,
    headers: { 'X-API-Key': KEY, 'Content-Type': 'application/json' },
    body: body ? JSON.stringify(body) : undefined
  })
  return resp.json()
}

async function main() {
  // 创建任务
  const { data: { taskId } } = await request('POST', '/api/dev/tasks', {
    title: 'Node.js 翻译', videoPath: '/path/to/video.mp4',
    sourceLanguage: 'en', targetLanguage: 'zh'
  })
  console.log('任务 ID:', taskId)

  // 轮询
  while (true) {
    const { data } = await request('GET', `/api/dev/tasks/${taskId}/status`)
    console.log(`  状态: ${data.status}  进度: ${data.progress}%`)
    if (data.status === 'completed' || data.status === 'failed') break
    await new Promise(r => setTimeout(r, 3000))
  }

  // 获取结果
  const { data: result } = await request('GET', `/api/dev/tasks/${taskId}/export`)
  console.log('导出路径:', result.exportPath)
}
main()

Java

import com.google.gson.*;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;

public class VideoTranslate {
    private static final String BASE = "http://127.0.0.1:9527";
    private static final String KEY = "dk_your_api_key_here";
    private static final Gson gson = new Gson();
    private static final HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30)).build();

    static JsonObject request(String method, String path, JsonObject body)
            throws Exception {
        var b = HttpRequest.newBuilder().uri(URI.create(BASE + path))
                .header("X-API-Key", KEY)
                .header("Content-Type", "application/json");
        if (body != null) b.method(method,
            HttpRequest.BodyPublishers.ofString(gson.toJson(body)));
        else b.method(method, HttpRequest.BodyPublishers.noBody());
        var r = client.send(b.build(), HttpResponse.BodyHandlers.ofString());
        return JsonParser.parseString(r.body()).getAsJsonObject();
    }

    public static void main(String[] args) throws Exception {
        var body = new JsonObject();
        body.addProperty("title", "Java 翻译");
        body.addProperty("videoPath", "/path/to/video.mp4");
        body.addProperty("sourceLanguage", "en");
        body.addProperty("targetLanguage", "zh");
        var resp = request("POST", "/api/dev/tasks", body);
        String taskId = resp.getAsJsonObject("data").get("taskId").getAsString();
        System.out.println("任务 ID: " + taskId);

        while (true) {
            var r = request("GET", "/api/dev/tasks/" + taskId + "/status", null);
            var d = r.getAsJsonObject("data");
            System.out.printf("  状态: %s  进度: %d%%%n",
                d.get("status").getAsString(), d.get("progress").getAsInt());
            if (d.get("status").getAsString().matches("completed|failed")) break;
            Thread.sleep(3000);
        }

        resp = request("GET", "/api/dev/tasks/" + taskId + "/export", null);
        System.out.println("导出: " + resp.getAsJsonObject("data")
            .get("exportPath").getAsString());
    }
}

Go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "time"
)

const Base = "http://127.0.0.1:9527"
const Key  = "dk_your_api_key_here"

var client = &http.Client{Timeout: 30 * time.Second}

func request(method, path string, body []byte) []byte {
    var r io.Reader
    if body != nil { r = bytes.NewReader(body) }
    req, _ := http.NewRequest(method, Base+path, r)
    req.Header.Set("X-API-Key", Key)
    req.Header.Set("Content-Type", "application/json")
    resp, _ := client.Do(req)
    defer resp.Body.Close()
    b, _ := io.ReadAll(resp.Body)
    return b
}

func main() {
    b, _ := json.Marshal(map[string]any{
        "title": "Go 翻译", "videoPath": "/path/to/video.mp4",
        "sourceLanguage": "en", "targetLanguage": "zh",
    })
    var resp struct { OK bool `json:"ok"`; Data struct { TaskID string `json:"taskId"` } `json:"data"` }
    json.Unmarshal(request("POST", "/api/dev/tasks", b), &resp)
    fmt.Println("任务 ID:", resp.Data.TaskID)

    for {
        var r struct { OK bool `json:"ok"`; Data struct {
            Status string `json:"status"`; Progress int `json:"progress"`
        } `json:"data"` }
        json.Unmarshal(request("GET", "/api/dev/tasks/"+resp.Data.TaskID+"/status", nil), &r)
        fmt.Printf("  状态: %s  进度: %d%%\n", r.Data.Status, r.Data.Progress)
        if r.Data.Status == "completed" || r.Data.Status == "failed" { break }
        time.Sleep(3 * time.Second)
    }

    var exp struct { OK bool `json:"ok"`; Data struct { ExportPath string `json:"exportPath"` } `json:"data"` }
    json.Unmarshal(request("GET", "/api/dev/tasks/"+resp.Data.TaskID+"/export", nil), &exp)
    fmt.Println("导出:", exp.Data.ExportPath)
}

Kotlin

import com.google.gson.*
import java.net.URI
import java.net.http.*
import java.time.Duration

val BASE = "http://127.0.0.1:9527"
val KEY = "dk_your_api_key_here"
val gson = Gson()
val client = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(30)).build()

fun request(method: String, path: String, body: JsonObject? = null)
    : JsonObject {
    val b = HttpRequest.newBuilder().uri(URI.create(BASE + path))
        .header("X-API-Key", KEY)
        .header("Content-Type", "application/json")
    if (body != null) b.method(method,
        HttpRequest.BodyPublishers.ofString(gson.toJson(body)))
    else b.method(method, HttpRequest.BodyPublishers.noBody())
    val r = client.send(b.build(), HttpResponse.BodyHandlers.ofString())
    return JsonParser.parseString(r.body()).asJsonObject
}

fun main() {
    val body = JsonObject().apply {
        addProperty("title", "Kotlin 翻译")
        addProperty("videoPath", "/path/to/video.mp4")
        addProperty("sourceLanguage", "en")
        addProperty("targetLanguage", "zh")
    }
    val resp = request("POST", "/api/dev/tasks", body)
    val taskId = resp.getAsJsonObject("data").get("taskId").asString
    println("任务 ID: $taskId")

    while (true) {
        val r = request("GET", "/api/dev/tasks/$taskId/status")
        val d = r.getAsJsonObject("data")
        println("  状态: ${d.get("status").asString}  进度: ${d.get("progress").asInt}%")
        if (d.get("status").asString in listOf("completed", "failed")) break
        Thread.sleep(3000)
    }

    val r = request("GET", "/api/dev/tasks/$taskId/export")
    println("导出: ${r.getAsJsonObject("data").get("exportPath").asString}")
}