使用WWWForm将列表传递给Web服务

时间:2018-04-15 15:34:33

标签: c# unity3d

我一直在保存这个HashSet字符串中的数据,我想将该HashSet发送到php文件(Web服务)。这只是我想要做的事情的例子。在应用程序中我正在处理列表的长度,大约是20。

我的问题是,有没有办法将列表传递给WWWForm?如果没有,还有其他办法吗?

string CreateUserURL = "localhost:81/ARFUR/InsertUser.php";
// Use this for initialization
void Start () {
    HashSet<string> list = new HashSet<string>();
}

// Update is called once per frame
void Update () {
    if(Input.GetKeyDown(KeyCode.Space)) CreateUser(inputUserName, inputPassword);
}

public void CreateUser(string username, string password){
    WWWForm form = new WWWForm();
    list.Add(username);
    list.Add(password);
    // What I want to do 
    form.AddField("list", list);
    WWW www = new WWW(CreateUserURL, form);

}

1 个答案:

答案 0 :(得分:1)

首先,请注意HashSet<string> list = new HashSet<string>();函数中声明了Start,这使它成为局部变量,因此您将无法在该函数之外访问它。将其声明为Start函数,以便您可以从CreateUser函数访问它:

要发送HashSet,请将其循环播放,然后致电form.AddField将当前HashSet添加到表单中。使用“list []”(注意'[]')作为AddField函数中的字段名称,以便您可以轻松访问服务器端的HashSet(使用php),如下所示: / p>

$_POST['list'][0];
$_POST['list'][1];
$_POST['list'][2];

这样的事情:

string CreateUserURL = "localhost:81/ARFUR/InsertUser.php";
HashSet<string> list = new HashSet<string>();

string inputUserName = null;
string inputPassword = null;

// Use this for initialization
void Start()
{

}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space)) CreateUser(inputUserName, inputPassword);
}

public void CreateUser(string username, string password)
{
    WWWForm form = new WWWForm();
    list.Add(username);
    list.Add(password);

    //Loop through each one and send
    foreach (var item in list)
    {
        //Add each one to the Field
        form.AddField("list[]", item);
    }

    WWW www = new WWW(CreateUserURL, form);
}

虽然这可以解决您的问题,但我建议您使用json序列化数据,然后发送数据而不是当前的方法。请参阅this帖子中的带有Json 的 POST请求部分,了解如何将数据作为json从Unity发送到服务器。