curl 请求C# Unity3D

igetnqfo  于 2022-11-13  发布在  C#
关注(0)|答案(1)|浏览(285)

我有一个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
}
ztmd8pv5

ztmd8pv51#

正如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等。
你也可以为你的数据创建一个模型类,然后把promptnsize属性放入其中。然后,你可以用JsonUtility.ToJson(dalleRequest)把它转换成JSON。或者,如果你愿意,你可以把这些值作为方法的参数,然后在发送请求的同时创建字符串。

相关问题