标签:WWW return string 使用 localPath Unity www error
一: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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。