UnityWebRequest http json通信

unity3d 提供了一个用于http通信的类叫:UnityWebRequest,它是www的替代者,所以建议使用这个类。我们这个例子以json格式与服务器通信。这里使用的json组件是:Newtonsoft

首先,服务器使用springboot 的http restful服务,接收请求的代码如下:

@RequestMapping("logic")

 public DeferredResult logic(@RequestBody LogicMessage param, @RequestHeader HttpHeaders httpHeaders, HttpServletRequest request, HttpServletResponse response) {

}

这果直接使用@RequestBody,让spring负责json和对象的转换。

下面是客户端的代码:

publicvoidRequest(object message,RequestCallback callback)

    {        

            StartCoroutine(SendRequest(message, callback));

    }

    privateIEnumerator SendRequest(object message,RequestCallback callback)

    {

        stringdata = JsonConvert.SerializeObject(message);

        Debug.Log("向服务器发送请求:"+ data);

        byte[] bodyRaw = Encoding.UTF8.GetBytes(data);

UnityWebRequest request = new UnityWebRequest(uri, "POST");

        request.uploadHandler = new UploadHandlerRaw(bodyRaw);

        request.SetRequestHeader("Content-Type", "application/json;charset=utf-8");

        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

        yieldreturn webClient.SendWebRequest();

        if (webClient.isNetworkError)

        {

            Debug.Log("http 请求错误:"+ webClient.error);

        } else        {

            stringresult = webClient.downloadHandler.text;

            HttpResponseResult responseObj = JsonConvert.DeserializeObject(result);

            callback(responseObj);

        }

    }

欢迎加群交流,QQ群:66728073,197321069,398808948.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容