Unity www.progress始终返回0

时间:2016-06-07 08:44:02

标签: c# web unity3d

Unity 5.3.4p1 Mac OS X 10.11.5

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;

public class TestWWW : MonoBehaviour {

    // Use this for initialization
    void Start () {
        Dictionary<string, string> headers = new Dictionary<string, string>();
        headers["Api-key"] = "sorry-i-cant-post-this";
        headers["Content-Type"] = "application/json";
        string url =  "http://sorry-i-cant-post-this";
        var req = string.Format(
            "{{\"major\":{0},\"minor\":{1},\"patch\":{2},\"release\":{3},\"notice\":{4}}}",
            0, 0, 0, 40, 0
        );
        byte[] postData = Encoding.UTF8.GetBytes(req);

        var www = new WWW(url, postData, headers);
        StartCoroutine(F(www));
    }

    IEnumerator F(WWW www) {
        while(!www.isDone) {
            Debug.Log(www.progress);
            yield return null;
        }
        if(www.error == null)
            Debug.Log("Done");
        else 
            Debug.Log(www.error);

    }

    // Update is called once per frame
    void Update () {

    }
}

此代码始终打印0,因为F(WWW www)函数的循环无法完成。

我使用Charles监控,发现响应代码是405方法不允许。

,请求是

POST /api/client/v2 HTTP/1.1 User-Agent: UnityPlayer/5.3.4p1 (http://unity3d.com) Host: http://sorry-i-cant-post-this Accept: */* Accept-Encoding: identity Api-key: sorry-i-cant-post-this Content-Length: 55 Content-Type: application/json X-Unity-Version:
5.3.4p1

{"major":0,"minor":0,"patch":0,"release":40,"notice":0}

有什么问题吗?

或者它只是一个Unity错误?

感谢!!!

最后,我发现这是因为我打开了ShadowSocks。

1 个答案:

答案 0 :(得分:1)

当服务器未返回内容长度标题时,会发生这种情况。在您的服务器代码中,您应该添加标头Content-Length:,后跟您要发送给客户端的数据大小。

如果仍无法解决问题,请使用UnityWebRequest API。移植问题中的代码以使用UnityWebRequest代替WWW

// Use this for initialization
void Start()
{

    string url = "http://sorry-i-cant-post-this";
    var req = string.Format(
        "{{\"major\":{0},\"minor\":{1},\"patch\":{2},\"release\":{3},\"notice\":{4}}}",
        0, 0, 0, 40, 0
    );

    UnityEngine.Networking.UnityWebRequest www = UnityEngine.Networking.UnityWebRequest.Post(url, req);
    www.SetRequestHeader("Api-key", "sorry-i-cant-post-this");
    www.SetRequestHeader("Content-Type", "application/json");

    StartCoroutine(F(www));
}

IEnumerator F(UnityEngine.Networking.UnityWebRequest www)
{
    www.downloadHandler = new UnityEngine.Networking.DownloadHandlerBuffer();
    www.Send();

    while (!www.isDone)
    {
        Debug.Log(www.downloadProgress);
        yield return null;
    }

    if (www.isError)
    {
        Debug.Log(www.error);
    }
    else
    {
        Debug.Log("Done");
        Debug.Log("Downloaded: " + www.downloadHandler.text);

        // Or retrieve results as binary data
        byte[] results = www.downloadHandler.data;
    }

}

// Update is called once per frame
void Update()
{

}