unity3d - 从 Unity 到 Flask 的 POST 请求导致“空”值
问题描述
在让这个演示服务器工作后,我可以将 GET 请求从它返回给 Unity,但是当我尝试使用 POST 请求将数据从 Unity 发送到本地服务器时,它只会显示null
添加到服务器中的值。这是我在 Unity 中使用的代码:
IEnumerator Upload()
{
WWWForm form = new WWWForm();
form.AddField("charge","+4/3");
form.AddField("name", "doubletop");
using (UnityWebRequest www = UnityWebRequest.Post("http://localhost:5000/quarks/", form))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
}
我会得到“表格上传完成!” 在控制台中,GET 请求将起作用,但这些null
值不断出现。
解决方案
在这个示例中,我将 Upload() 方法修改为 PostRequest() ,现在它可以工作了!
这是完整的代码:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class HTTP : MonoBehaviour
{
void Start()
{
// A correct website page.
StartCoroutine(GetRequest("localhost:5000/quarks"));
PostData();
StartCoroutine(GetRequest("localhost:5000/quarks"));
// A non-existing page.
//StartCoroutine(GetRequest("https://error.html"));
}
IEnumerator GetRequest(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError)
{
Debug.Log(pages[page] + ": Error: " + webRequest.error);
}
else
{
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
}
}
[Serializable]
public class Quark
{
public string name;
public string charge;
}
public void PostData()
{
Quark gamer = new Quark();
gamer.name = "doublebottom";
gamer.charge = "4/3";
string json = JsonUtility.ToJson(gamer);
StartCoroutine(PostRequest("http://localhost:5000/quarks", json));
}
IEnumerator PostRequest(string url, string json)
{
var uwr = new UnityWebRequest(url, "POST");
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend);
uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
uwr.SetRequestHeader("Content-Type", "application/json");
//Send the request then wait here until it returns
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
}
推荐阅读
- javascript - npm 模块“csv-db”不工作
- xml - Powershell中的动态对象操作?
- python - ImportError:没有名为 sysconfig 的模块--无法使 pip 工作
- html - 如何使用 vue.draggable 拖动多行?
- ios - '不安全指针
' 不能转换为 'UnsafePointer<_>' - c++ - 如何知道 std::string 是否编码正确?
- android - if 和 return 语句
- javascript - 使用其他表单字段上传表单
- ruby-on-rails - 使用 Ruby 和 GraphQL 解决 NameError 问题:未初始化的常量 UserMutations?
- postgresql - 在 PL/pgSQL 函数内的动态命令中使用数组