I'm testing out dynamically generating images using OpenAI API in Unity. Amusingly, I actually generated most of this code from 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...
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 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
}
}
}
Any idea what's going wrong? Apologies if it's something obvious, never made web requests in Unity before.
CodePudding user response:
UnityWebRequests url-encodes content before submitting the request. This messes up the formatting. see: https://answers.unity.com/questions/1163204/prevent-unitywebrequestpost-from-url-encoding-the.html
using httpClient worked for me.