Unity使用UnityWebRequest发送http请求

本文介绍如何在Unity中使用litJson库创建JSON格式的数据,并通过UnityWebRequest或UniRx库发送这些数据到服务器。文中提供了具体的代码实现示例,包括设置HTTP头部、发送POST请求及处理响应。
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);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值