You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UnityWebRequest向MySQL发送数据为空的问题求助

问题分析

核心问题是UnityWebRequest.Post的重载使用错误:直接传递JSON字符串时,Unity默认会将其当作application/x-www-form-urlencoded格式的表单数据处理,而非JSON请求体发送,导致服务器无法解析有效内容。同时UI状态逻辑存在异步问题,协程启动后会立刻恢复按钮状态,导致加载提示失效。

修复方案

1. 修正UnityWebRequest请求构造方式

放弃UnityWebRequest.Post(string url, string postData)重载,手动构造POST请求,将JSON作为原始请求体发送:

IEnumerator LogInAuthenticate()
{      
    // 将JSON字符串转换为UTF-8字节数组
    byte[] jsonBytes = System.Text.Encoding.UTF8.GetBytes(Value);
    
    // 创建空POST请求,指定请求方法
    using (UnityWebRequest www = new UnityWebRequest(Url, "POST"))
    {
        // 设置上传处理器为原始字节数组
        www.uploadHandler = new UploadHandlerRaw(jsonBytes);
        // 设置下载处理器用于接收响应
        www.downloadHandler = new DownloadHandlerBuffer();
        // 指定Content-Type为JSON格式
        www.SetRequestHeader("Content-Type", "application/json");          
        
        yield return www.SendWebRequest();
        
        // 处理请求结果
        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError ("Web Issue : "+ www.error);
        }
        else
        {
            string responseText = www.downloadHandler.text;
            Debug.Log("Log Message : " + responseText);
            if (responseText.StartsWith("Authenticate Successfully"))
            {
                Debug.Log("Sucess :"+ responseText);
            }
            else
            {
                Debug.LogError("Log Issue : " + responseText);
            }
        }
        
        // 无论请求成功失败,恢复UI状态
        loginButton.SetActive(true);
        loadingImg.SetActive(false);
    }
}

2. 修复UI状态逻辑

删除LoginButton方法末尾的以下两行代码:

loginButton.SetActive(true);
loadingImg.SetActive(false);

将UI状态恢复逻辑移到协程的请求处理完成后(如上述代码所示),确保加载状态保持到请求结束。

额外验证

确认Debug.Log(Value)能输出正确的JSON格式(例如{"email":"test@example.com","password":"123456"})。若输出异常,检查Credentials类的JsonUtility.ToJson:JsonUtility仅序列化公共字段,你的email和password已满足要求;若继承了Singleton基类,确保基类字段未干扰序列化(如标记[NonSerialized])。

原方式失效原因

UnityWebRequest.Post(string url, string postData)重载专为表单键值对设计(格式如email=xxx&password=xxx),Unity会自动编码为application/x-www-form-urlencoded格式,与服务器期望的application/json请求体不匹配,导致服务器收到空JSON。

内容的提问来源于stack exchange,提问作者Ghazanfar Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 08:40:33