c# - UnityWebRequest not sending POST data
问题描述
When Unity sends the POST request it doesn't pass the POST data, so the server returns an error (it gets the server response). I've seen that several people had a similar issue and it got fixed by adding www.chunkedTransfer = false;
, however, that doesn't work for me.
I've also seen that some people use WWWForm
instead of IMultipartFormSection
, but I haven't tried it because it is deprecated.
I'm using PHP, but I've also tried it with Perl and it didn't work either. When I manually send a POST request everything works normally, so it seems the issue is in Unity. I'm new to Unity, so any help would be appreciated. I'm using the current latest version, 2018.2.18f1 Personal.
My code is pretty much the same as the official Unity documentation for sending POST request, but apparently it doesn't work. Here is my code:
C#:
public void Click() {
StartCoroutine(PostRequest("http://127.0.0.1/test.php", "help"));
}
IEnumerator PostRequest(string url, string data) {
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("data=" + data));
UnityWebRequest www = UnityWebRequest.Post(url, formData);
www.chunkedTransfer = false;
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
} else {
Debug.Log(www.downloadHandler.text);
}
}
PHP:
<?php echo "Server received: " . $_POST["data"]; ?>
解决方案
Christoph Lütjen指出,尽管new MultipartFormDataSection("data", data)
官方文档示例使用new MultipartFormDataSection("field1=foo&field2=bar")
.
更改它以new MultipartFormDataSection("data", data)
解决问题。
推荐阅读
- wordpress - 如何在我的网站 (wordpress) 的标题菜单中为一个特定项目着色?
- python - 如何在 GCP 上部署超过 100 mb 的压缩文件?
- linux - 如何在 Bash 中检查文件是否具有带有正则表达式的扩展名(任何扩展名)?
- c# - 如何在 ASP.NET Core 3 MVC 中向非反应项目添加单个反应?
- java - bash:javac:找不到命令[Sublime Text 3]
- python - 为什么 jupyter notebook 在 Anaconda Prompt 中不起作用?
- javascript - 同时在循环中运行函数
- tsql - 从字符串转换日期和/或时间时,SQLCMD 给出转换失败
- algorithm - Scheme - 生成列表的所有不同排列
- django - 从 DjangoTemplateLanguage 到 re_path() 的多个参数