WWW POST / GET请求将无法从服务器返回的最新数据/ URL [英] WWW POST/GET request won't return the latest data from server/url

查看:831
本文介绍了WWW POST / GET请求将无法从服务器返回的最新数据/ URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 使用UnityEngine; 
使用UnityEngine.UI; System.Collections中使用
;
使用系统;
使用Newtonsoft.Json;
使用System.Collections.Generic;
:使用System.IO;

公共类TextChange:MonoBehaviour {

//使用这个初始化
WWW搞定;
公共静态字符串getreq;
文本文字;
布尔continueRequest = FALSE;

无效的start()
{
StartCoroutine(WaitForRequest());
文本= GetComponent<文本>();
}

//更新是每帧
无效更新()
{

}
$ B $调用一次b私人IEnumerator的WaitForRequest()
{
如果(continueRequest)
产量突破;

continueRequest = TRUE;

浮动requestFrequencyInSec = 1006米; //每5秒
WaitForSeconds WAITTIME =新WaitForSeconds(requestFrequencyInSec)后更新;

,而(continueRequest)
{
字符串URL =API链接到这里;
WWW得到=新的WWW(URL);
产量得到回报;
getreq = get.text;
//检查错误
如果(get.error == NULL)
{
JSON字符串= @getreq;
名单,LT; MyJSC>数据= JsonConvert.DeserializeObject<名单,LT; MyJSC>>(JSON);
INT L = data.Count;
text.text =数据:+数据[1 - 1] .content;
}
,否则
{
的debug.log(错误 - >!+ get.error);
}

收益率的回报WAITTIME; //等待requestFrequencyInSec时间
}
}

无效stopRequest()
{
continueRequest = FALSE;
}
}

公共类MyJSC
{
公共字符串_id;
公共字符串作者;
公共字符串的内容;
公共字符串_V;
公共字符串日期;
}


解决方案

这是发生,因为资源缓存。在服务器上启用



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



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



2 。使具有独特的时间戳每个请求。时间应在的Unix 格式。



此方法不会在iOS 工作。你的罚款,因为这是 HoloLens



例如,如果您的网址是 http://url.com/file.rar ,追加?T = currentTime的结尾。 currentTime的的Unix 格式的实际时间。



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



代码

 字符串getUTCTime()
{
System.Int32 unixTimestamp =(System.Int32)(System.DateTime.UtcNow.Subtract(新的System.DateTime(1970,1,1)))TotalSeconds。
返回unixTimestamp.ToString();
}

私人的IEnumerator WaitForRequest()
{
字符串URL =API链接到这里+ + getUTCTime()T =?;
WWW得到=新的WWW(URL);
产量得到回报;
getreq = get.text;
//检查错误
如果(get.error == NULL)
{
JSON字符串= @getreq;
名单,LT; MyJSC>数据= JsonConvert.DeserializeObject<名单,LT; MyJSC>>(JSON);
INT L = data.Count;
text.text =数据:+数据[1 - 1] .content;
}
,否则
{
的debug.log(错误 - >!+ get.error);
}
}



3 停用缓存在客户端通过提供和修改的Cache-Control 和<$ C $侧C>杂注的请求头。



设置的Cache-Control 标题最大年龄= 0,无缓存,无店铺然后设置杂注 标题 NO-缓存



我建议你用 UnityWebRequest做到这一点而不是 WWW 类。首先,包括使用UnityEngine.Networking;



代码



  IEnumerator的WaitForRequest (字符串URL)
{

UnityWebRequest WWW = UnityWebRequest.Get(URL);
www.SetRequestHeader(缓存控制,最大年龄= 0,无缓存,无店);
www.SetRequestHeader(杂注,无缓存);

产量返回www.Send();
如果(www.isError)
{
的debug.log(www.error);
}
,否则
{
的debug.log(收到+ www.downloadHandler.text);
}
}


I am creating a HoloLens app using Unity which has to take data from a REST API and display it. I am currently using WWW datatype to get the data and yield return statement in a coroutine that will be called from the Update() function. When I try to run the code, I get the latest data from the API but when someone pushes any new data onto the API, it does not automatically get the latest data in real time and I have to restart the app to see the latest data. My Code:

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

    // 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<MyJSC> data = JsonConvert.DeserializeObject<List<MyJSC>>(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;
}

解决方案

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

这篇关于WWW POST / GET请求将无法从服务器返回的最新数据/ URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆