Unity Http Post請求之Json參數


使用的是Litjson

    void Start()
    {
        //使用litJson創建json格式的參數數據
        JsonData data = new JsonData();
        data["與后端協商好的參數名"] = "你要寫入的參數";
        byte[] postBytes = System.Text.Encoding.Default.GetBytes(data.ToJson());

        //使用原生UnityWebRequest(推薦)
        StartCoroutine(UnityWebRequestPost("你的url", postBytes));

        //使用UniRx
        ObservableWWW.Post("你的url", postBytes, new Dictionary<string, string>() { { "Content-Type", "application/json" } })
                     .Subscribe(result => Debug.Log(result));
    }

    IEnumerator UnityWebRequestPost(string url, byte[] postBytes)
    {
        UnityWebRequest request = new UnityWebRequest(url, "POST");

        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        yield return request.SendWebRequest();
        Debug.Log("Status Code: " + request.responseCode);
        if (request.isNetworkError || request.isHttpError)
        {
            Debug.LogError(request.error);
        }
        else
        {
            Debug.Log(request.downloadHandler.text);
        }
    }

 


免責聲明!

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



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