long polling with UnityWebRequest

I have a server that can send commands to the Unity application. I’m using long polling. I create delayed POST requests and await for server response for up to one minute. When server has some command, it responds with this command. If there are no commands - the request is getting timed out and a new one is sent.

The server accepts POST requests with raw json in the body.

Here is my code using WWW:

    void getServerCommand()
    {
        Dictionary<string, object> data = new Dictionary<string, object>();
        data.Add("command", "getServerCommand");
        data.Add("gatewayId", gatewayId);
        data.Add("timeout", cloudCommandTimeoutDuration);
        string jsonString = JsonConvert.SerializeObject(data);
        byte[] body = Encoding.UTF8.GetBytes(jsonString);

        Dictionary<string,string> headers = new Dictionary<string, string>();
        headers.Add("Content-Type", "application/json");

        WWW www = new WWW(cloudUrl, body, headers);

        StartCoroutine(WaitForCommand(www));
    }

    IEnumerator WaitForCommand(WWW www)
    {
        yield return www;

        if (www.isDone)
        {
            Debug.Log("Command accepted.");
        }
        else
        {
            Debug.Log("WWW Error: " + www.error + ", body:" + www.text);
        }

        processResponse(www.text);
    }

I’m trying to upgrade to UnityWebRequest and this is what I have right now:

    IEnumerator Post(string url, string bodyJsonString)
    {
        var request = new UnityWebRequest(url, "POST");
        byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
        request.uploadHandler = new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = new DownloadHandlerBuffer();
        request.uploadHandler.contentType = "application/json";
        yield return request.SendWebRequest();
        Debug.Log("Status Code: " + request.responseCode);
        request.Dispose();
        doSendNewRequest = true;
    }

But this returns Status Code: 409 instead of waiting for the response from the server.

Is it possible to do long polling with UnityWebRequest?

Which Unity version are you using?
In all version starting with 2017.1 WWW is implemented on top of UnityWebRequest, so it is possible for sure.

The only difference I can quickly find is that WWW sets chunkedTransfer = false; on UnityWebRequest, while by default it might be true on your version (in latest versions it is by default false).
You might also want to check the returned content (download handler text property), maybe it tells the more detail reason why it returns 409.

1 Like

Thank you for the quick reply.
Sorry for the confusion. The issue was that I used built-in JsonUtility.ToJson that couldn’t serialize dictionary, so the request body was {}. I’ve plugged in the Newtonsoft Json.Net library and it worked like a charm.