Unity_Post 请求与Json解析

########创建post请求参数########

JsonData jdata = new JsonData();
 jdata["sn"] = System.Guid.NewGuid().ToString();
 jdata["deviceNo"] = SystemInfo.deviceUniqueIdentifier;
#if UNITY_ANDROID
        jdata["platform"] = 1;
        StartCoroutine(SendPost("请求地址", jdata));
#elif UNITY_IPHONE
        jdata["platform"] = 2;
       StartCoroutine(SendPost("请求地址", jdata));
#endif

##############接收的JSON文件格式#################

{
  "code": 1001,
  "total": 1,
  "data": [
    {
      "acType": 1,
      "index": 1,
      "current": 1,
      "condition": 1
    }]

###########发送Post请求########

IEnumerator SendPost(string _url, JsonData data)
    {
        UnityWebRequest request = new UnityWebRequest(_url, "POST");

        byte[] postBytes = System.Text.Encoding.Default.GetBytes(data.ToJson());

        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("CLEARANCE", "YOUR_TARGET_SERVER");
        request.timeout = 5;
        yield return request.SendWebRequest();

        if (request.responseCode == 200)
        {
            string text = request.downloadHandler.text;

           JsonData jData = JsonMapper.ToObject(text);
           JsonData _jData = jData["data"];
           int achDataNum = int.Parse(jData["total"].ToString());
           for (int i = 0; i < achDataNum; i++) {
           _task.acType = int.Parse(_jData[i]["acType"].ToString());
            taskS.Add(_task);
         }

你可能感兴趣的:(Unity)