Unity进行接口请求案例

View Code
    public IEnumerator GetInterface()
    {
        // 定义请求的URL
        string TargetUrl = string.Format("{0}/api/Player", "https://localhost:7096");
        Debug.LogFormat("请求的url:{0}", TargetUrl);
        // 创建一个UnityWebRequest对象,使用GET方法
        using (UnityWebRequest webRequest = UnityWebRequest.Get(TargetUrl))
        {
            // 发送请求并等待响应
            yield return webRequest.SendWebRequest();
            if (webRequest.result == UnityWebRequest.Result.Success)
            {
                Debug.Log(webRequest.downloadHandler.text);
            }
            else
            {
                // 如果发生错误,打印错误信息
                Debug.LogError(webRequest.error);
            }
        }
    }
View Code

其中用作测试的Player数据类:

    public class Player
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public int Age { get; set; }
    }

  

 

其中Post方法,需要注意,当有json上传时,需要设置头格式

***

        request.SetRequestHeader("Content-Type", "application/json");

  

posted @ 2025-10-11 17:26  SummerTrainnn  阅读(5)  评论(0)    收藏  举报