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

Unity中调用OpenAI图像生成API返回400错误请求的原因排查

Unity调用OpenAI图片生成API报无效JSON错误的解决方法

核心问题在于你使用的UnityWebRequest.Post(string url, string postData)重载默认会将传入的字符串当作表单数据处理,即便手动设置了Content-Type为application/json,Unity依然会对该字符串进行URL编码,导致实际发送到OpenAI的请求体格式被破坏,从而触发"invalid JSON"错误。

修正方案是直接传递原始JSON字节数组作为请求体,避免Unity自动编码处理,具体代码修改如下:

public class PlayerScript : MonoBehaviour
{
    // Replace API_KEY with your actual API key
    private string API_KEY = "<api_key>";
    private string API_URL = "https://api.openai.com/v1/images/generations";

    void Start()
    {
        StartCoroutine(GetImage());
    }

    IEnumerator GetImage()
    {
        // Create a request body with the prompt "Player"
        string requestBody = "{\"prompt\": \"Player\",\"n\": 1,\"size\": \"128x128\"}";
        // 将JSON字符串转换为字节数组
        byte[] jsonBytes = System.Text.Encoding.UTF8.GetBytes(requestBody);

        // 创建UnityWebRequest实例,指定POST方法
        UnityWebRequest www = new UnityWebRequest(API_URL, "POST");
        // 设置上传处理器,传入原始JSON字节数组
        www.uploadHandler = new UploadHandlerRaw(jsonBytes);
        // 设置下载处理器(用于接收返回数据)
        www.downloadHandler = new DownloadHandlerBuffer();

        // Set the authorization header with the API key
        www.SetRequestHeader("Authorization", "Bearer " + API_KEY);
        // Set the content type header
        www.SetRequestHeader("Content-Type", "application/json");

        // Send the request
        yield return www.SendWebRequest();

        // Check for errors
        if (www.isNetworkError || www.isHttpError)
        {
            Debug.LogError(www.error);
        }
        else
        {
            // 处理返回结果,比如解析JSON获取图片URL
            string responseText = www.downloadHandler.text;
            Debug.Log("Response: " + responseText);
        }

        // 释放资源
        www.Dispose();
    }
}

关键修改说明:

  • 使用UploadHandlerRaw包装JSON字节数组,确保请求体以原始JSON格式发送,不会被Unity修改。
  • 显式创建UnityWebRequest实例并指定POST方法,替代原有的字符串重载。
  • 添加DownloadHandlerBuffer用于接收API返回的响应数据(按需处理结果)。
  • 最后调用Dispose()释放请求资源,避免内存泄漏。

内容的提问来源于stack exchange,提问作者Michael Huang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:25:39