如标题所示,代码如下所示。我尝试过设置chunkedTransfer=false、Content应用程序/ JSON、WWWForm、手动构建JSON对象和HttpClient。对于Content应用程序/json,API甚至没有命中。对于其他人来说,身体是一个空的物体。我不知道在StackOverflow、YouTube、Unity和所有其他资源中存在什么问题。
从今天早上开始,我将使用Newtonsoft.Json来序列化JSON主体。我认为现在最大的问题是,当我设置webRequest.SetRequestHeader("Content-Type", "application/json");时,API路由甚至没有接收到请求。
async Task<string> makeRequest()
{
string url = API_BASE + "/users";
Dictionary<string, string> body = new Dictionary<string, string>();
body.Add("username", username);
body.Add("password", password);
body.Add("email", email);
using (UnityWebRequest webRequest = UnityWebRequest.Post(url, JsonConvert.SerializeObject(body)))
{
await webRequest.SendWebRequest();
string result = Encoding.UTF8.GetString(webRequest.downloadHandler.data);
if (webRequest.result != UnityWebRequest.Result.Success)
{
JSONNode error = JSON.Parse(result);
registerAndLoginError.GetComponent<Text>().text = error["error"]["message"];
registerAndLoginError.SetActive(true);
return "";
}
}
BasicLogin();
return "";
}发布于 2021-06-28 14:14:08
因此,我在其他地方看到了这个解决方案,但我继续忽略它,因为它是乏味的,似乎是一些应该解决的问题。不过,我现在一点也不关心。
UnityWebRequest.Put而不是UnityWebRequest.PostwebRequest.method = "POST";webRequest.SetRequestHeader("Content-Type", "application/json");这是可行的,但感觉很糟糕,没有任何意义。
发布于 2021-06-28 07:16:43
内置Dictionary**!** JsonUtility 不支持--它遵循与检查器相同的序列化规则,参见脚本序列化。
=> JsonUtility.ToJson(body)只返回"",或者在最好的情况下返回"{}"。
尝试创建“手动”的JSON字符串,比如。
var json = "{\"username\":\""+username+"\", \"password\":\""+password+"\", \"email\":\""+email+"\"}";或者使用不同的库,例如Newtonsoft .NET Json (可作为通过PackageManager包装提供),它支持直接(反)序列化集合和字典。
https://stackoverflow.com/questions/68156230
复制相似问题