Unity中WWW类使用
作者:互联网
一:WWW介绍
WWW类是Unity网络开发中使用频率非常高的一个工具类,主要提供一般HTTP访问的功能,以及从网络上动态的下载图片,声音,视频资源等等。 目前WWW支持的协议有http://,https://,file://,ftp://,其中file是访问本地文件。WWW支持使用Get和Post方式进行表单的上传。 虽然新版本已经不建议使用了,但是嘛,我还是记录记录。
1.1 WWW下载本地StreamingAssets资源
当我们本地加载StreamingAssets资源的时候,需要使用WWW进行操作。具体代码如下所示:
class FileUtil
{
/// <summary>
///读取StreamingAssets中的文件
/// </summary>
/// <param name="path">StreamingAssets下的文件路径</param>
public static string GetTextFromStreamingAssets(string path)
{
string localPath = "";
if (Application.platform == RuntimePlatform.Android)
{
localPath = Application.streamingAssetsPath + "/" + path;
}
else
{
localPath = "file:///" + Application.streamingAssetsPath + "/" + path;
}
WWW www = new WWW(localPath);
if (www.error != null)
{
Debug.LogError("error while reading files : " + localPath);
return ""; //读取文件出错
}
while (!www.isDone) { }
//Debug.Log("File content : " + www.text);
return www.text;
}
二:WWW类网络请求
Unity的WWW类主要支持GET 和POST两种方式。GET方式请求的内容会附在url的后面一起做为URL向服务器发送请求(请求的内容使用&符号隔开);而POST方式中向服务器发送请求的数据是以一个数据包的形式和url分开传送的,相比GET方式,POST的优点:
1.比GET安全;
2.传输数据没有长度限制; 综上所述:在项目中使用POST方式多一些。
/* GET方式
*
* 1、采用Get方式进行数据传输时,不稳定不安全
* 2、采用Get方式进行数据传输时,数据长度受限
* 3、采用Get方式进行数据传输时,必须将请求链接与请求内容
* 绑定,一同发送至服务器, 请求内容之间用&隔开
*
*/
IEnumerator WWWGet()
{
using (WWW www = new WWW("http://127.0.0.1:9997/gameInit?uid=7"))
{
yield return www;
if (www.error != null)
Debug.Log(www.error);
else
Debug.Log(www.text.ToString());
//自行解析即可
}
}
IEnumerator WWWPost()
{
string m_info = null;
Dictionary<string, string> hash = new Dictionary<string, string>();
hash.Add("Content-Type", "application/json");
string data = "{\"Name\":\"zhangsan\",\"Password\":\"123456\"}";
byte[] bs = System.Text.UTF8Encoding.UTF8.GetBytes(data);
WWW www = new WWW("http://127.0.0.1:9997/login", bs, hash);
yield return www;
if (www.error != null) {
m_info = www.error;
yield return null;
}
m_info = www.text;
print(m_info);
www.Dispose();//释放
}
标签:WWW,return,string,使用,localPath,Unity,www,error 来源: https://blog.csdn.net/zhuyuqiang1238/article/details/116501077