unity3d 提供了一個用於http通訊的類叫:UnityWebRequest,它是www的替代者,因此建議使用這個類。咱們這個例子以json格式與服務器通訊。這裏使用的json組件是:Newtonsoftweb
首先,服務器使用springboot 的http restful服務,接收請求的代碼以下:spring
@RequestMapping("logic") public DeferredResult<Object> logic(@RequestBody LogicMessage param, @RequestHeader HttpHeaders httpHeaders, HttpServletRequest request, HttpServletResponse response) { }
這果直接使用@RequestBody,讓spring負責json和對象的轉換。json
下面是客戶端的代碼:springboot
publicvoidRequest(object message,RequestCallback callback)服務器
{restful
StartCoroutine(SendRequest(message, callback));app
}spa
privateIEnumerator SendRequest(object message,RequestCallback callback)3d
{rest
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.