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

Unity中POST请求报错422 Unprocessable Entity,如何修复?

问题原因分析

你遇到的422 Unprocessable Entity错误,核心原因是请求头声明的格式与实际发送的请求体格式不匹配:

  • 你设置了content-type: application/json请求头,告诉服务器要接收JSON格式的数据
  • 但实际通过WWWForm生成的是application/x-www-form-urlencoded格式的表单数据,服务器解析时发现格式不符,因此报错
修复方案

方案1:发送JSON格式请求体(推荐,匹配声明的请求头)

构造JSON字符串作为请求体,转换为字节数组后发送:

public IEnumerator POST()
{
    Dictionary<string, string> headers = new Dictionary<string, string>();
    headers.Add("cache-control", "no-cache");
    headers.Add("content-type", "application/json");
    headers.Add("x-anketolog-apikey", "***");

    // 构造JSON格式的请求数据
    var requestData = new { survey_id = "***" };
    string jsonContent = JsonUtility.ToJson(requestData);
    byte[] postData = System.Text.Encoding.UTF8.GetBytes(jsonContent);

    var query = new WWW("https://apiv2.anketolog.ru/survey/answer/list", postData, headers);
    yield return query;

    if (query.error != null)
    {
        Debug.Log("Server does not respond : " + query.error);
    }
    else
    {
        // 打印完整响应内容,服务器通常会返回具体错误提示
        Debug.Log("Server responded : " + query.text);
    }
    query.Dispose();
}

方案2:修改请求头匹配表单格式(若服务器支持)

如果该API接口允许接收表单格式数据,调整请求头即可:

public IEnumerator POST()
{
    Dictionary<string, string> headers = new Dictionary<string, string>();
    headers.Add("cache-control", "no-cache");
    // 移除JSON类型头,或替换为表单格式头
    headers.Add("content-type", "application/x-www-form-urlencoded");
    headers.Add("x-anketolog-apikey", "***");

    var data = new WWWForm();
    data.AddField("survey_id", "***");
    var query = new WWW("https://apiv2.anketolog.ru/survey/answer/list", data.data, headers);
    yield return query;

    if (query.error != null)
    {
        Debug.Log("Server does not respond : " + query.error);
    }
    else
    {
        Debug.Log("Server responded : " + query.text);
    }
    query.Dispose();
}
额外建议
  1. 优先查看该API的官方文档,确认接口要求的请求格式(JSON/表单),严格遵循文档规范
  2. 打印服务器返回的query.text内容,里面通常包含具体的错误原因(比如字段名错误、survey_id无效等),可根据提示进一步排查
  3. 若使用Unity 2017及以上版本,建议改用UnityWebRequest替代已过时的WWW类,功能更完善且稳定性更高

内容的提问来源于stack exchange,提问作者Sec Lewrie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:00:12