UnityWebRequest http post json通信
JSON插件下载地址:https://github.com/JamesNK/Newtonsoft.Json/releases
unity3d 提供了一个用于http通信的类叫:UnityWebRequest,它是www的替代者,所以建议使用这个类。我们这个例子以json格式与服务器通信。这里使用的json组件是:Newtonsoft
首先,服务器使用springboot 的http restful服务,接收请求的代码如下:
@RequestMapping("logic") public DeferredResult<Object> logic(@RequestBody LogicMessage param, @RequestHeader HttpHeaders httpHeaders, HttpServletRequest request, HttpServletResponse response) { }
这果直接使用@RequestBody,让spring负责json和对象的转换。
下面是客户端的代码:
public IEnumerator HttpPost(string url, Object param,HttpJsonResponse response){ string jsonParam = JsonConvert.SerializeObject(param); byte[] body = Encoding.UTF8.GetBytes(jsonParam); UnityWebRequest unityWeb = new UnityWebRequest(url,"POST"); unityWeb.uploadHandler = new UploadHandlerRaw(body); unityWeb.SetRequestHeader("Content-Type", "application/json;charset=utf-8"); unityWeb.downloadHandler = new DownloadHandlerBuffer(); yield return unityWeb.SendWebRequest(); if(unityWeb.isDone){ string result = unityWeb.downloadHandler.text; response(result); } else { Debug.Log("Http 请求失败"); Debug.Log(unityWeb.error); } }
欢迎加群交流,QQ群:66728073,197321069,398808948.