WWW/UnityWebRequest POST/GET request won’t return the latest data from server/url

This is happening because resources caching is enabled on the Server.

Three possible solutions I know about:

1.Disable resources caching on the server. Instructions are different for every web server. Usually done in .htaccess.

2.Make each request with unique timestamp. The time should in Unix format.

This method will not work on iOS. You are fine since this is for HoloLens.

For example, if your url is http://url.com/file.rar, append ?t=currentTime at the end. currentTime is the actual time in Unix Format.

Full example url: http://url.com/file.rar?t=1468475141

Code:

string getUTCTime()
{
    System.Int32 unixTimestamp = (System.Int32)(System.DateTime.UtcNow.Subtract(new System.DateTime(1970, 1, 1))).TotalSeconds;
    return unixTimestamp.ToString();
}

private IEnumerator WaitForRequest()
{
    string url = "API Link goes Here" + "?t=" + getUTCTime();
    WWW get = new WWW(url);
    yield return get;
    getreq = get.text;
    //check for errors
    if (get.error == null)
    {
        string json = @getreq;
        List<MyJSC> data = JsonConvert.DeserializeObject<List<MyJSC>>(json);
        int l = data.Count;
        text.text = "Data: " + data[l - 1].content;
    }
    else
    {
        Debug.Log("Error!-> " + get.error);
    }
}

3.Disable Cache on the client side by supplying and modifying the Cache-Control and Pragma headers in the request.

Set Cache-Control header to max-age=0, no-cache, no-store then set Pragma header to no-cache.

I suggest you do this with UnityWebRequest instead of the WWW class. First, Include using UnityEngine.Networking;.

Code:

IEnumerator WaitForRequest(string url)
{

    UnityWebRequest www = UnityWebRequest.Get(url);
    www.SetRequestHeader("Cache-Control", "max-age=0, no-cache, no-store");
    www.SetRequestHeader("Pragma", "no-cache");

    yield return www.Send();
    if (www.isError)
    {
        Debug.Log(www.error);
    }
    else
    {
        Debug.Log("Received " + www.downloadHandler.text);
    }
}

Leave a Comment