在Unity中的三種Http通信方式

1、WWW(基于協(xié)程,不適用于線程)

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(基于協(xié)程,不適用于線程)

IEnumerator GetRequest()
{
    string url = "https://www.baidu.com/";
    using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
    {

        //設(shè)置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();

        //設(shè)置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,同步接口,阻塞等待結(jié)果返回,適用于線程)

在Unity中,使用C#原生的HttpWebRequest,若是數(shù)據(jù)較大,會卡頓,主要因為Unity單線程,HttpWebRequest不能異步執(zhí)行,但適用于多線程。

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ReadWriteTimeout = ReadWriteTimeOut;
request.Timeout = TimeOutWait;
//設(shè)置Range值,斷點續(xù)傳
request.AddRange((int)startPos);
HttpWebResponse respone = (HttpWebResponse)request.GetResponse();
Stream ns = respone.GetResponseStream();
ns.ReadTimeout = TimeOutWait;
byte[] bytes = new byte[oneReadLen];
int readSize = ns.Read(bytes, 0, oneReadLen); // 讀取第一份數(shù)據(jù)
while (readSize > 0)
{
     fs.Write(bytes, 0, readSize); // 將下載到的數(shù)據(jù)寫入臨時文件
     // 往下繼續(xù)讀取
     readSize = ns.Read(bytes, 0, oneReadLen);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容