在统一的WebGL构建中发布JSON请求失败(但不是本地发布)

时间:2018-10-14 19:24:30

标签: c# json unity3d restsharp unity-webgl

我有以下C#发布请求代码:

public static string getJSON()
var client = new RestClient("");
          var request = new RestRequest(Method.POST);
          var httpWebRequest = (HttpWebRequest)WebRequest.Create("url") 
          request.AddHeader("cache-control", "no-cache");
          request.AddParameter("undefined", "{\r\n\t\"application\": {\r\n\t\t\"id\":3\r\n\t},\r\n\t\"luminaire\": {\r\n\t\t\"id\":60\r\n\t},\r\n\t\"room\": {\r\n\t\t\"length\":" + roomSize.x + ",\r\n\t\t\"width\":" + roomSize.z+ ",\r\n\t\t\"height\":"+roomSize.y+",\r\n\t\t\"discretizedPitch\":{\r\n\t\t\t\"x\":0.6,\r\n\t\t\t\"y\":0.6\r\n\t\t}\r\n\t}\r\n}", ParameterType.RequestBody);
          IRestResponse response = client.Execute(request);
          return response.Content;

现在这可以正常使用,但是当我制作一个Webbuild时,会遇到与null相关的问题。

我还尝试将代码重写为unitynetwork代码(使用Sending http requests in C# with Unity

    public static void getJSON(){

        var s = StartCoroutine(PostRequest("url", "\"application\": {\"id\":3},\"luminaire\": {\"id\":60},\"room\": {\"length\":" + roomSize.x + ",\"width\":" + roomSize.z + ",\"height\":" + roomSize.y + ",\"discretizedPitch\":{\"x\":0.6,\"y\":0.6}}"));

    }

    string res = "";

    IEnumerator PostRequest(string url, string json)
    {
        var uwr = new UnityWebRequest(url, "POST");
        byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
        uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend);
        uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        uwr.SetRequestHeader("Content-Type", "application/json");

        //Send the request then wait here until it returns
        yield return uwr.SendWebRequest();

        if (uwr.isNetworkError)
        {
            Debug.Log("Error While Sending: " + uwr.error);
            res = "error";
        }
        else
        {
            res = uwr.downloadHandler.text;
            Debug.Log("Received: " + uwr.downloadHandler.text);
        }
    }

但是这只会引发服务器500错误而不是有用的任何消息,有人知道如何将第一个代码移植到unitynetwork代码中,或者为什么第一个代码在webgl中给出了null异常(但在普通代码中却没有)?

1 个答案:

答案 0 :(得分:0)

好吧,我现在很蠢,

json当然应该是

"{\"application\": {\"id\":3},\"luminaire\": {\"id\":60},\"room\": {\"length\":" + roomSize.x + ",\"width\":" + roomSize.z + ",\"height\":" + roomSize.y + ",\"discretizedPitch\":{\"x\":0.6,\"y\":0.6}}}"

为了相同,一个简单的复制粘贴错误。