You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity调用DeepL API的WebRequest出现400错误,求助排查

问题排查与修复方案

1. 目标语言代码格式错误

DeepL API要求目标语言代码为大写格式(例如EN代表英语,ES代表西班牙语),如果传入的targetLanguage是小写(如en),会触发参数无效的400错误。

2. 请求Content-Type未正确设置

直接用字符串构造POST数据时,UnityWebRequest可能没有自动添加DeepL API要求的application/x-www-form-urlencoded请求头,导致请求格式不被识别。建议改用WWWForm构造表单数据,Unity会自动处理正确的请求头:

private void TranslateText(string textToTranslate, string targetLanguage)
{
    string deepLApiUrl = "https://api-free.deepl.com/v2/translate";
    WWWForm form = new WWWForm();
    form.AddField("source_lang", "auto");
    form.AddField("target_lang", targetLanguage.ToUpper()); // 强制转为大写格式
    form.AddField("text", textToTranslate); // WWWForm会自动编码特殊字符,无需手动处理

    UnityWebRequest webRequest = UnityWebRequest.Post(deepLApiUrl, form);
    webRequest.SetRequestHeader("Authorization", "DeepL-Auth-Key " + apiKey);
    webRequest.SetRequestHeader("User-Agent", "YourApp/1.2.3");

    StartCoroutine(SendTranslationRequest(webRequest));
}

3. API密钥有效性问题

确认apiKey变量是否正确填写了DeepL免费版密钥(免费版密钥以fx-开头),密钥错误或为空也会返回400错误。

4. 文本编码重复处理问题

你手动调用Uri.EscapeDataString处理文本,但若UnityWebRequest后续再次自动编码,会导致参数格式混乱。改用WWWForm后无需手动编码,它会自动处理特殊字符的编码工作。


内容的提问来源于stack exchange,提问作者Bill Rousseau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:30:06