当前位置: 首页> 汽车> 新车 > 帮推广平台_杨和勒流网站建设_西安高端模板建站_潍坊网站开发公司

帮推广平台_杨和勒流网站建设_西安高端模板建站_潍坊网站开发公司

时间:2025/7/10 17:12:33来源:https://blog.csdn.net/suiusoar/article/details/142396052 浏览次数: 0次
帮推广平台_杨和勒流网站建设_西安高端模板建站_潍坊网站开发公司

题意:为什么 OpenAI 图像生成 API 在 Unity 中返回 400 Bad Request 错误?

问题背景:

I'm testing out dynamically generating images using OpenAI API in Unity. Amusingly, I actually generated most of this code from chatGPT.

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

The Error response is: "Your request contained invalid JSON: Expecting value: line 1 column 1 (char 0)". But I cant see anything wrong with the json formatting of my requestbody...

错误响应是:‘你的请求包含无效的 JSON:期待值:第 1 行第 1 列 (字符 0)’。但我看不出我的请求体的 JSON 格式有什么问题……

I also found this other question which is probably failing for the same reason, whatever it is: 

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

Here is my code:        以下是我的代码:

public class PlayerScript : MonoBehaviour
{// Replace API_KEY with your actual API keyprivate 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 POSTUnityWebRequest www = UnityWebRequest.Post(API_URL, requestBody);// Set the authorization header with the API keywww.SetRequestHeader("Authorization", "Bearer " + API_KEY);// Set the content type headerwww.SetRequestHeader("Content-Type", "application/json");// Send the requestyield return www.SendWebRequest();// Check for errorsif (www.isNetworkError || www.isHttpError){Debug.LogError(www.error);}else{// do stuff}}
}

Any idea what's going wrong? Apologies if it's something obvious, never made web requests in Unity before.

知道哪里出了问题吗?如果问题显而易见请见谅,我以前从未在 Unity 中发过网络请求。

问题解决:

UnityWebRequests url-encodes content before submitting the request. This messes up the formatting. see: 

UnityWebRequests 在提交请求之前会对内容进行 URL 编码,这会导致格式混乱。参见:prevent UnityWebRequest.Post() from Url-Encoding the data ? - Questions & Answers - Unity Discussions

using httpClient worked for me.

“使用 httpClient 对我来说是有效的。

关键字:帮推广平台_杨和勒流网站建设_西安高端模板建站_潍坊网站开发公司

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: