WWW / UnityWebRequest POST / GET请求不会从server / url返回最新数据

我正在使用Unity创建一个HoloLens应用程序,它必须从REST API获取数据并显示它。 我目前正在使用WWW数据类型来获取将从Update()函数调用的协程中的数据和yield return语句。 当我尝试运行代码时,我从API获取最新数据但是当有人将任何新数据推送到API时,它不会实时自动获取最新数据,我必须重新启动应用程序以查看最新数据。 我的代码:

using UnityEngine; using UnityEngine.UI; using System.Collections; using System; using Newtonsoft.Json; using System.Collections.Generic; using System.IO; public class TextChange : MonoBehaviour { // Use this for initialization WWW get; public static string getreq; Text text; bool continueRequest = false; void Start() { StartCoroutine(WaitForRequest()); text = GetComponent(); } // Update is called once per frame void Update() { } private IEnumerator WaitForRequest() { if (continueRequest) yield break; continueRequest = true; float requestFrequencyInSec = 5f; //Update after every 5 seconds WaitForSeconds waitTime = new WaitForSeconds(requestFrequencyInSec); while (continueRequest) { string url = "API Link goes Here"; WWW get = new WWW(url); yield return get; getreq = get.text; //check for errors if (get.error == null) { string json = @getreq; List data = JsonConvert.DeserializeObject<List>(json); int l = data.Count; text.text = "Data: " + data[l - 1].content; } else { Debug.Log("Error!-> " + get.error); } yield return waitTime; //Wait for requestFrequencyInSec time } } void stopRequest() { continueRequest = false; } } public class MyJSC { public string _id; public string author; public string content; public string _v; public string date; } 

发生这种情况是因为在服务器上启用了资源缓存。

我知道的三种可能的解决方案

1Disable 服务器上的资源缓存。 每个Web服务器的说明都不同。 通常在.htaccess完成。

2.使用唯一的时间戳使每个请求生效。 时间应该是Unix格式。

此方法不适用于iOS 。 你很好,因为这是为HoloLens

例如,如果您的url是http://url.com/file.rar ,请在末尾添加?t=currentTimecurrentTime是Unix格式的实际时间。

完整示例url: http://url.com/file.rar?t=1468475141http://url.com/file.rar?t=1468475141

代码

 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 data = JsonConvert.DeserializeObject>(json); int l = data.Count; text.text = "Data: " + data[l - 1].content; } else { Debug.Log("Error!-> " + get.error); } } 

3 。 通过在请求中提供和修改Cache-ControlPragma标头,在客户Disable缓存。

Cache-Control 标头设置为max-age=0, no-cache, no-store然后将Pragma 标头设置为no-cache

我建议你用UnityWebRequest而不是WWW类来做这UnityWebRequest 。 首先,包括using UnityEngine.Networking;

代码

 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); } }