在Unity中的三种Http通信方式
1、WWW(基于协程,不适用于线程)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()); } www.Dispose();//释放 }}IEnumerator WWWPost(){ 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) { Debug.Log(www.error); } else { Debug.Log(www.text.ToString()); } www.Dispose();//释放}2、UnityWebRequest(基于协程,不适用于线程)
IEnumerator GetRequest(){ string url = "https://www.baidu.com/"; using (UnityWebRequest webRequest = UnityWebRequest.Get(url)) { //设置header webRequest.SetRequestHeader("Content-Type", "application/json"); webRequest.SetRequestHeader("authKey", "leohui"); yield return webRequest.SendWebRequest(); if (webRequest.isHttpError || webRequest.isNetworkError) { Debug.LogError(webRequest.error); } else { Debug.Log(webRequest.downloadHandler.text); } }}IEnumerator PostRequest(){ string url = "https://www.baidu.com/"; using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST")) { string data = "{\"Name\":\"zhangsan\",\"Password\":\"123456\"}"; byte[] bodyRaw = Encoding.UTF8.GetBytes(data); webRequest.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw); webRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); //设置header webRequest.SetRequestHeader("Content-Type", "application/json"); webRequest.SetRequestHeader("authKey", "leohui"); yield return webRequest.SendWebRequest(); if (webRequest.isHttpError || webRequest.isNetworkError) { Debug.LogError(webRequest.error); } else { Debug.Log(webRequest.downloadHandler.text); } }}3、HttpWebRequest(C#原生的HttpWebRequest,同步接口,阻塞等待结果返回,适用于线程)
在Unity中,使用C#原生的HttpWebRequest,若是数据较大,会卡顿,主要因为Unity单线程,HttpWebRequest不能异步执行,但适用于多线程。
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;request.ReadWriteTimeout = ReadWriteTimeOut;request.Timeout = TimeOutWait;//设置Range值,断点续传request.AddRange((int)startPos);HttpWebResponse respone = (HttpWebResponse)request.GetResponse();Stream ns = respone.GetResponseStream();ns.ReadTimeout = TimeOutWait;byte[] bytes = new byte;int readSize = ns.Read(bytes, 0, oneReadLen); // 读取第一份数据while (readSize > 0){ fs.Write(bytes, 0, readSize); // 将下载到的数据写入临时文件 // 往下继续读取 readSize = ns.Read(bytes, 0, oneReadLen);}
页:
[1]