I have an API Curl request, that returns a link:
curl https://api.openai.com/v1/images/generations \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-d '{
"prompt": "A cute baby sea otter",
"n": 2,
"size": "1024x1024"
}'
How can I request the link through Curl in my C# script in Unity Engine? Thanks!
This is what I have so far:
void Start () {
StartCoroutine ("FillAndSend");
}
public IEnumerator FillAndSend() {
#Curl request here
}
CodePudding user response:
As Dai stated out, you can use UnityWebRequest for this. You have few options to send it with. This is one way of doing it;
private const string YourApiKey = "3152-6969-1337";
void Start()
{
var json = "{\"prompt\": \"A cute baby sea otter\",\"n\": 2,\"size\": \"1024x1024\"}";
StartCoroutine(FillAndSend(json));
}
public IEnumerator FillAndSend(string json)
{
using (var request = new UnityWebRequest("https://api.openai.com/v1/images/generations", "POST"))
{
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", $"Bearer {YourApiKey}");
request.SetRequestHeader("Accept", " text/plain");
request.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(json));
request.downloadHandler = new DownloadHandlerBuffer(); // You can also download directly PNG or other stuff easily. Check here for more information: https://docs.unity3d.com/Manual/UnityWebRequest-CreatingDownloadHandlers.html
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError) // Depending on your Unity version, it will tell that these are obsolote. You can try this: request.result != UnityWebRequest.Result.Success
{
Debug.LogError(request.error);
yield break;
}
Debug.Log(request.downloadHandler.text);
var response = request.downloadHandler.data; // Or you can directly get the raw binary data, if you need.
}
}
You can also use UnityWebRequest.Post(string uri, string postData)
method, or you can use WWWForm
class to post with form, instead of JSON etc.
You can also create a model class for your data, then put prompt
, n
, and size
properties in it. Afterwards, you can convert it to JSON with JsonUtility.ToJson(dalleRequest)
. Or if you want, you can take those values as parameters for the method, then create the string while sending the request.