gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:15:48 25 4
gpt4 key购买 nike

我一直在这个 HashSet 字符串中保存数据,我想将该 HashSet 发送到一个 php 文件(网络服务)。这只是我尝试做的事情的一个例子。在应用程序中,我正在处理大约 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);

}

最佳答案

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


发送您的 HashSet , 遍历它并调用 form.AddField添加当前 HashSet到表格。使用“list[]”(注意“[]”)作为 AddField 中的字段名称功能,以便您可以轻松访问 HashSet在服务器端(使用 php)如下:

$_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 请求部分发布有关如何从 Unity 将数据作为 json 发送到服务器的帖子。

关于c# - 使用 WWWForm 将列表传递给 Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49843677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com