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.


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM