zoukankan      html  css  js  c++  java
  • 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.


  • 相关阅读:
    Rust语言学习笔记(11)
    Rust语言学习笔记(10)
    Rust语言学习笔记(9)
    Rust语言学习笔记(8)
    趣味编程:静夜思(Rust版)
    Python sorted()
    Python 魔法方法
    Python filter()
    Python的map和reduce
    Python函数的参数
  • 原文地址:https://www.cnblogs.com/wgslucky/p/9863766.html
Copyright © 2011-2022 走看看