gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:47:49 26 4
gpt4 key购买 nike

我正在测试在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com