Unity的http访问工具UnityWebRequest使用

http访问工具类

unity 原来有个http访问的工具类WWW,参考http://www.superzhan.cn/?p=112。在新版本的Unity中,推出了新的工具类UnityWebRequest,可以代替原来的WWW类。

简单的Get访问

UnityWebRequest包含多个静态方法,可以创建一个UnityWebRequest对象,调用SendWebRequest正式发送请求。在协程返回结果后,需要判断是否有错误,再做处理。

using System.Collections;
using System.Collections.Generic;
using System.Net;
using UnityEngine;
using UnityEngine.Networking;
public class NewBehaviourScript : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(GetRequest());
    }

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

            yield return webRequest.SendWebRequest();

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
            }
            else
            {
                Debug.Log(webRequest.downloadHandler.text);
            }
        }
    }
}

Http post访问

项目中post访问提交的数据都是json格式的,这里需要对提交的数据uploadHandler做处理,把提交的数据抓换为byte数组。 如果提交的是form表单,可以参考官方文档。

public IEnumerator PostRequest(string methodName, string jsonString, Action<string> callback)
    {
        string url = baseUrl + methodName;
        using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
            webRequest.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
            webRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();

            yield return webRequest.SendWebRequest();

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                if (callback != null)
                {
                    callback(null);
                }
            }
            else
            {
                if (callback != null)
                {
                    callback(webRequest.downloadHandler.text);
                }
            }
        }
    }

http header设置

访问http接口时,考虑到安全方面的问题,可以在提交的数据里面加上一个key字符串,用于身份验证。

这个key字符串可以放到http 的 header中。

设置header方法

 webRequest.SetRequestHeader(Key, Value);

完整工具代码封装

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.Networking;
using System.Text;

/// <summary>
/// Http Request SDK 
/// </summary>
public class HttpTool : MonoBehaviour
{

    private static HttpTool _instacne = null;
    public string baseUrl = "https://127.0.0.1:3000/";
    public string sKey = "zoo_visit_key";

    Dictionary<string, string> requestHeader = new Dictionary<string, string>();  //  header
    public static HttpTool Instance
    {
        get
        {
            if (_instacne == null)
            {
                Debug.LogError("Awake error");
            }
            return _instacne;
        }
    }

    void Awake()
    {
        DontDestroyOnLoad(gameObject);
        HttpTool._instacne = gameObject.GetComponent<HttpTool>();

         //http header 的内容
        requestHeader.Add("Content-Type", "application/json");
        requestHeader.Add("sKey", sKey);

    }

    public void Get(string methodName, Action<string> callback)
    {
        StartCoroutine(GetRequest(methodName, callback));
    }
    public IEnumerator GetRequest(string methodName, Action<string> callback)
    {
        string url = baseUrl + methodName;
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {
            //设置header
            foreach (var v in requestHeader)
            {
                webRequest.SetRequestHeader(v.Key, v.Value);
            }
            yield return webRequest.SendWebRequest();

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                if (callback != null)
                {
                    callback(null);
                }
            }
            else
            {
                if (callback != null)
                {
                    callback(webRequest.downloadHandler.text);
                }
            }
        }
    }

   //jsonString 为json字符串,post提交的数据包为json
    public void Post(string methodName,string jsonString, Action<string> callback)
    {
        StartCoroutine(PostRequest(methodName,jsonString,callback));
    }
    public IEnumerator PostRequest(string methodName, string jsonString, Action<string> callback)
    {
        string url = baseUrl + methodName;
       // Debug.Log(string.Format("url:{0} postData:{1}",url,jsonString));
        using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
            webRequest.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
            webRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();

            foreach (var v in requestHeader)
            {
                webRequest.SetRequestHeader(v.Key, v.Value);
            }
            yield return webRequest.SendWebRequest();

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                if (callback != null)
                {
                    callback(null);
                }
            }
            else
            {
                if (callback != null)
                {
                    callback(webRequest.downloadHandler.text);
                }
            }
        }
    }
}

参考

更多的使用方法,可以参考官方文档。
https://docs.unity3d.com/2019.1/Documentation/ScriptReference/Networking.UnityWebRequest.html

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文节选自洪流学堂公众号技术专栏《大话Unity2019》,未经允许不可转载。 洪流学堂公众号回复专栏,查看更多专...
    洪智阅读 6,406评论 0 10
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,172评论 1 32
  • 今天领导出差了,就感觉今天过得特别轻松,平时他在的时候感觉压力特别大,也是奇怪。 明天不知道他回不回来,希望不能回...
    贤者谙客阅读 70评论 0 0
  • 关于如何决策,是个让我越来越感兴趣的话题,也愈发意识到它的重要性。 昨天真正“系统学习”德扑,我觉得每一次决策都与...
    史妍阅读 195评论 0 0
  • 再过几个小时就是你21周岁的生日了。 首先要祝你生日快乐。 白云苍狗,人的成长真的是缓慢而又迅速,也不知怎么的...
    向北_d36c阅读 352评论 0 0