UnityWebRequest发送POST请求时请求体为空的原因排查咨询
问题原因分析
服务器代码中使用的@RequestParam注解,是专门用来解析**表单格式(application/x-www-form-urlencoded)的请求参数;而你的Unity代码发送的是JSON格式(application/json)**的请求体,两者数据格式不匹配,导致服务器无法解析到请求内容。
Python代码能正常运行,是因为requests.post的data参数默认会把字典转换成表单格式发送,刚好匹配服务器的接收方式。
两种解决方案
方案一:修改Unity代码,发送表单格式请求
保持服务器代码不变,调整Unity请求的参数格式和请求头:
string jsonUrl = "http://127.0.0.1/backend/login"; // 构造表单键值对,注意对特殊字符转义 string data = $"userName={UnityWebRequest.EscapeURL(playerEmail)}&password={UnityWebRequest.EscapeURL(playerPassword)}"; Debug.Log(data); var request = new UnityWebRequest(jsonUrl, "POST"); byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(data); request.uploadHandler = new UploadHandlerRaw(bodyRaw); request.downloadHandler = new DownloadHandlerBuffer(); // 设置表单格式的Content-Type request.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded"); yield return request.SendWebRequest(); // 补充响应处理逻辑 if (request.result != UnityWebRequest.Result.Success) { Debug.LogError($"请求失败: {request.error}"); } else { Debug.Log($"响应内容: {request.downloadHandler.text}"); }
方案二:修改服务器代码,接收JSON格式请求
保持Unity代码不变,修改服务器的参数接收注解为@RequestBody,用来解析JSON格式请求体:
@PostMapping("/backend/login") @ResponseBody public Map<String, String> login(@RequestBody Map<String, String> requestBody) { Map<String, String> result = new HashMap<>(); System.out.println(requestBody); if (userService.selectCountByNameAndPassword(requestBody.get("userName"), requestBody.get("password")) > 0) { result.put("type", "1"); result.put("message", "success"); } else { result.put("type", "0"); result.put("message", "wrong username or password"); } return result; }
选择建议
- 如果不需要调整现有服务器逻辑,优先选方案一;
- 如果后续需要传输更复杂的参数结构(比如嵌套对象),优先选方案二,JSON格式扩展性更强。
内容的提问来源于stack exchange,提问作者徐亦昶
相关产品推荐
相关产品推荐

