json - 为什么 OpenAI 图像生成 Api 在 Unity 中返回 400 错误请求?

标签 json unity3d post openai-api unitywebrequest

我正在测试在 Unity 中使用 OpenAI API 动态生成图像。有趣的是,我实际上从 chatGPT 生成了大部分代码。

错误响应是:“您的请求包含无效的 JSON:预期值:第 1 行第 1 列(字符 0)”。但是我看不出我的请求体的 json 格式有什么问题...

我还发现了另一个可能出于同样原因而失败的问题,无论它是什么:Why does Post request to OpenAI in Unity result in error 400?

这是我的代码:

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\"}";
        // Create a UnityWebRequest and set the request method to POST
        UnityWebRequest www = UnityWebRequest.Post(API_URL, requestBody);

        // 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
        {
            // do stuff
        }
    }
}

知道出了什么问题吗?很抱歉,如果这很明显,以前从未在 Unity 中发出过 Web 请求。

最佳答案

UnityWebRequest 提交请求前的url编码内容。这搞乱了格式。参见:https://answers.unity.com/questions/1163204/prevent-unitywebrequestpost-from-url-encoding-the.html

使用 httpClient 对我有用。

关于json - 为什么 OpenAI 图像生成 Api 在 Unity 中返回 400 错误请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74846628/

相关文章:

php - 如何在一个提交按钮上禁用 JS 的情况下为访问者执行两个 POST 请求?

c# - 发布方法并使用某些值重定向而不使用 Form C#

json - 如何在 React 组件中访问 JSON?

c# - Unity Moving Player Leg 多人游戏

c# - 如何在纯 C# 中制作队列消息代理

android - 未找到 FirebaseAuthWebException。请验证 AAR

json - 如何使用 Alamofire 和 swift 4 为 Clarifai API 编写 POST 请求?

jquery - 将图像保存到 Json 文件

json - 使用 Newtonsoft.Json 解析 Json 字符串时出错

json - 无法使用 Scala circle json 库中 LocalDateTime 的自定义解码器反序列化对象