Unity网络连接之Post

Unity项目开发中经常使用到Post来获取服务器数据,那么该如何获取呢?在这里插入代码片

    string jsonData= "{\r\n  \"beginTime\": \"2021-05-18T03:17:52.624Z\",\r\n  \"endTime\": \"2021-05-18T03:17:52.624Z\",\r\n  \"farmId\":0,\r\n  \"topN\": 0\r\n}";
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(PostData(jsonData));
    }
    public IEnumerator PostData(string jsondata)
    {
        var url = "http://192.168.0.83:3206/api/test";
        byte[] databyte = Encoding.UTF8.GetBytes(jsondata);
        var _request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
        _request.uploadHandler =(UploadHandlerRaw) new UploadHandlerRaw(databyte);
        _request.downloadHandler = (DownloadHandlerBuffer) new DownloadHandlerBuffer();
        _request.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
        //_request.SetRequestHeader("access-control-allow-origin", "*");
        yield return _request.SendWebRequest();
        //Debug.Log(_request.responseCode);

        if (_request.result == UnityWebRequest.Result.ProtocolError||_request.result== UnityWebRequest.Result.DataProcessingError)
        {
            Debug.LogError(_request.error);
        }
        else
        {
            //Debug.Log(_request.downloadHandler.text);
            if (_request.downloadHandler.text.Length < 105)
            {
                Debug.Log("获取到的数据长度小于105"+":"+ _request.downloadHandler.text);
            }
            else
            {
                Debug.Log(_request.downloadHandler.text.Substring(1, 100));

            }
        }
    }

其中,jsondata是我们要传递过去的参数,是一串字符串。

在我们遇到需要设置其他复杂参数的时候要怎么做呢?

    private IEnumerator PostRequest(string mUrl, byte[] postData, Action<string> Callback, string contentType = "application/json", Dictionary<string, string> headDic=null)
    {
        using (UnityWebRequest webRequest = new UnityWebRequest(mUrl, UnityWebRequest.kHttpVerbPOST))
        {
            UploadHandler uploader = new UploadHandlerRaw(postData);
            webRequest.uploadHandler = uploader;
            webRequest.uploadHandler.contentType = contentType;  //设置HTTP协议的请求头,默认的请求头HTTP服务器无法识别
            if (headDic != null)
            {
                foreach (var VARIABLE in headDic)
                {
                    webRequest.SetRequestHeader(VARIABLE.Key,VARIABLE.Value);
                }
            }
            //这里需要创建新的对象用于存储请求并响应后返回的消息体,否则报空引用的错误
            DownloadHandler downloadHandler = new DownloadHandlerBuffer();
            webRequest.downloadHandler = downloadHandler;

            //Debug.Log(webRequest.uploadHandler.loginInfData.Length);

            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();

            if (webRequest.isNetworkError || webRequest.isHttpError)
            {
                Debug.LogError(webRequest.error + webRequest.isHttpError);
            }
            else
            {
                //string reciveStr = System.Text.Encoding.UTF8.GetString(webRequest.downloadedBytes);
                Callback(webRequest.downloadHandler.text);
            }
        }
    }

这个是一段需要设置多个参数的post代码,其中需要传递的参数有地址,参数,回调方法和Header设置

            byte[] postBytes = System.Text.Encoding.Default.GetBytes("{\"reqUserInfo\":{\"attrs\":[\"id\",\"regtime\",\"roomid\",\"authreward\"],\"props\":[200000001,200010002]}}");
            Dictionary<string, string> testhead = new Dictionary<string, string>();
            testhead.Add("X-UID", DataMgr.loginInfData.userid + "");
            AcceptNetData.Instance.PostRequestData("/fishhallapi/dress/operate?format=json".AddIP(), postBytes, ResponentChangeSkinData, "application/json", testhead);

这里面的参数是直接使用字符段传递的,还可以利用LitJson来设置传递

        private byte[] CreateByte(int id)
        {
            JsonData data = new JsonData();
            data["roomId"] = id;
            data["svrId"] = "";
            data["deployId"] = "264_819";
            data["pType"] = 1;
            data["roomCardId"] = "";
            return System.Text.Encoding.UTF8.GetBytes(data.ToJson());
        }

可以利用如此方法设置,更加直观,这个用来代替参数设置,但这里面怎么设置复杂参数我就不得而知了,例如我的roomCardidi需要设置成多个字符串,类似list类型的!有个猜想是需要设置复杂的的类的时候新建一个相对应的类,赋值好后序列化,接着转成字节数组就能用了。

你可能感兴趣的:(Unity,Unity3D,unity,unity3d)