Unity使用UnityWebRequest进行POST请求的时候遇到内存泄露问题

说明

有个项目接口要用POST请求,去后端请求数据,我使用UnityWebRequest这个API过程中遇到了内存泄漏的问题。
在这里插入图片描述

解决方法

在代码模块加了using(){},会自动释放UnityWebRequest

  IEnumerator PostInfo_IE(string url, string postData)
    {
    
    
        using (UnityWebRequest request = new UnityWebRequest(url,"POST"))
        {
    
    
            byte[] postBytes=Encoding.UTF8.GetBytes(postData);
            request.uploadHandler = new UploadHandlerRaw(postBytes);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");

            yield return request.SendWebRequest();

            if (!string.IsNullOrEmpty(request.error))
            {
    
    
                Debug.LogWarning(request.error);
            }
            else
            {
    
    
                try
                {
    
    
                    string iconInfoStr = "{\"IconList\":" + request.downloadHandler.text + "}";

                    iconModel.CurIconInfo.Value = JsonUtility.FromJson<IconInfo>(iconInfoStr);
                }
                catch (Exception e)
                {
    
    
                    iconModel.CurIconInfo.Value = null;
                }
            }
        }
    }

排除问题时发现一个了,如果是 using (UnityWebRequest request = UnityWebRequest.Post(url,postData)),还是会报内存泄漏的问题。最终改为 using (UnityWebRequest request = new UnityWebRequest(url,“POST”))问题解决。

猜你喜欢

转载自blog.csdn.net/weixin_44446603/article/details/128319286