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.


  • 相关阅读:
    CString与 char *之间的转换
    linux命令行打开图片
    CentOS7 NFS配置
    vs2010 Visula C++ 把CString 转换为string 类型
    1>LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
    mount 命令
    Centos7.0 Vmware10.0.3 网络桥接配置
    Notepad++ 连接远程 FTP 进行文件编辑
    安装PHP的mongodb驱动速记
    CentOS上安装MongoDB速记
  • 原文地址:https://www.cnblogs.com/wgslucky/p/9863766.html
Copyright © 2011-2022 走看看