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)函数的while循环无法完成。
我使用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。
当服务器不返回内容长度标头时,就会发生这种情况。在服务器代码中,应添加标头,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()
{
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句