我有一個 API Curl 請求,它回傳一個鏈接:
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"
}'
如何在 Unity Engine 的 C# 腳本中通過 Curl 請求鏈接?謝謝!
這是我到目前為止所擁有的:
void Start () {
StartCoroutine ("FillAndSend");
}
public IEnumerator FillAndSend() {
#Curl request here
}
uj5u.com熱心網友回復:
正如 Dai 所說,您可以為此使用 UnityWebRequest。您幾乎沒有選擇發送它。這是一種方法;
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.
}
}
您也可以使用UnityWebRequest.Post(string uri, string postData)方法,或者您可以使用WWWForm類來發布表單,而不是 JSON 等。
您還可以為您的資料創建一個模型類,然后將prompt、n和size屬性放入其中。之后,您可以使用JsonUtility.ToJson(dalleRequest). 或者,如果您愿意,可以將這些值作為方法的引數,然后在發送請求時創建字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/528138.html
