首页 > 解决方案 > 从 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值不断出现。

标签: unity3dflasklocalhostunitywebrequest

解决方案


在这个示例中,我将 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);
        }
    }
}

推荐阅读