unity3d 提供了一个用于http通信的类叫:UnityWebRequest,它是www的替代者,所以建议使用这个类。我们这个例子以json格式与服务器通信。这里使用的json组件是:Newtonsoft
首先,服务器使用springboot 的http restful服务,接收请求的代码如下:
@RequestMapping("logic")
publicDeferredResult 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.
网友评论