DEV Community

Piler
Piler

Posted on

[Unity] UnityWebRequest: A Native Collection has not been disposed, resulting in a memory leak.

Issue: Use UnityWebRequest POST with JSON may cause the error below.

private IEnumerator PostWithJson(string url, string json)
{
    using (UnityWebRequest request = UnityWebRequest.Post(url, "POST"))
    {
        request.SetRequestHeader("Content-Type", "application/json");

        byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json);
        using (UploadHandlerRaw uploadHandler = new UploadHandlerRaw(bodyRaw))
        {
            request.uploadHandler = uploadHandler;
            request.disposeUploadHandlerOnDispose = true;

            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(request.error);
            }
            else
            {
                Debug.Log(request.downloadHandler.text);
            }
            request.uploadHandler.Dispose();
            request.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Solution: Use HttpWebRequest instead.

private string PostWithJson_CSharp(string url, string json)
{
    //Debug.Log($"url:{url}, json:{json}");
    try
    {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(json);
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        Debug.Log(httpResponse.ProtocolVersion);
        using var streamReader = new StreamReader(httpResponse.GetResponseStream());
        var result = streamReader.ReadToEnd();
        return result;
    }
    catch (Exception e)
    {
        Debug.Log(e.Message);
        return null;
    };
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)