WWW 资源下载与表单提交

时间:2020-12-22 04:09:34

在注册与验证用户信息,以及非即时通信的游戏中,我们可以使用WWW类使用短链接来完成客户端与服务器数据的通信,今天我们将使用用POST方法来完成的用户注册与登录,在最后介绍下其它资源的加载。

首先使用POST完成注册:
场景中两个InputField用于输入名字与密码,一个Button提交注册。
Button绑定方法如下:

 using UnityEngine;
using System.Collections;
using UnityEngine.UI; public class RegisterAndLogin : MonoBehaviour
{
private string registerURL;
private InputField _name;
private InputField _pwd; void Awake()
{
_name = GameObject.Find("Name").GetComponent<InputField>();
_pwd = GameObject.Find("Pwd").GetComponent<InputField>();
registerURL = "http://..../wwwRegister.php";
} public void OnClickRegister ()
{
//定义WWWForm类用于存放POST的字段
WWWForm registerForm = new WWWForm();
//添加对应字段到表单,注意KEY要与服务器上一致
registerForm.AddField("name", _name.text);
registerForm.AddField("password", _pwd.text);
//协程开始注册
StartCoroutine(RegisterFun(registerURL, registerForm));
} IEnumerator RegisterFun(string url, WWWForm form)
{
WWW regi_www = new WWW(url, form);
yield return regi_www;
//得到服务器返回信息
string callBack = regi_www.text.Trim();
//服务器返回 “1”,注册成功
if (callBack.Equals(""))
{
Debug.Log("congratulations! register OK! (call back code:" + callBack + ")");
}
//否则失败
else
{
Debug.Log("register failed! (call back code:" + callBack + ")");
}
}
}

运行场景,可以看到注册成功如下:
WWW 资源下载与表单提交
重复注册导致失败:
WWW 资源下载与表单提交
数据库中已经有数据咯:
WWW 资源下载与表单提交

登录和注意相似,只是需要在服务器上加以判断,并返回信息就行,这里就不写了。

再使用读取个纹理图片的:

 void Start()
{
string urlTexture = "https://www.baidu.com/img/bd_logo1.png";
StartCoroutine (LoadTexture(urlTexture));
} //加载一张图片纹理
IEnumerator LoadTexture(string url)
{
WWW www = new WWW (url);
yield return www;
this.renderer.material.mainTexture = www.texture;
}

最后用GET来个读个JSON吧:
服务器上根据请求查询数据后格式化如下:
[{“id”:”1″,”name”:”\u5f6c\u5f6c”,”sex”:”\u5973″,”age”:”19″},
{“id”:”2″,”name”:”\u8d85\u8d85″,”sex”:”\u7537″,”age”:”24″},
{“id”:”8″,”name”:”\u5a01\u5a01″,”sex”:”\u7537″,”age”:”20″}]
脚本代码:

 using UnityEngine;
using System.Collections;
using LitJson; public class wwwScript : MonoBehaviour
{
//JSON模板类
public class Person
{
public string id ;
public string name;
public string sex;
public string age;
} void Start ()
{
//通过“?+键值对”指定请求内容
StartCoroutine (LoadText ("http://.../wwwGet.php?tablename=person"));
} IEnumerator LoadText(string url)
{
WWW www = new WWW (url);
yield return www;
Debug.Log ("loaded total data:" + www.text);
//Json处理
Person[] persons = JsonMapper.ToObject <Person[]> (www.text);
foreach (Person item in persons)
{
Debug.Log (item.id + item.name + item.age);
}
}
}

OK咯,相信通过上面的例子,大家一定可以举一反三,应付绝大部分WWW类数据提交与请求的问题了^_^