当前位置:   article > 正文

UnityWebRequest_unitywebrequest unityaction

unitywebrequest unityaction

前言

UnityWebRequest是新的网络请求Api,分为LLApi和HLApi,其中LLApi为低级api,所谓低级api是指只是提供最基本的api接口,然后需要通过不同的参数来确定请求方式。为此unity提供了高级api(HLApi)即对不同的功能进行了封装,以下基于HLApi做了简单封装。

1.简单封装代码

using System.Collections;
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections.Generic;
using System.IO;

public class WebRequestUtility : MonoBehaviour
{
    public static WebRequestUtility Instance;

    enum RequestType
    {
        TEXT_GET,
        TEXTUREE_GET,
        ASSETBUNDEL,
        POST
    }

    public void Get(string url,Action<UnityWebRequest> action)
    {
        StartCoroutine(Request(url,action,RequestType.TEXT_GET));
    }

    public void GetTexture(string url,Action<UnityWebRequest> action)
    {
        StartCoroutine(Request(url, action, RequestType.TEXTUREE_GET));
    }

    public void GetAssetBundle(string url,Action<UnityWebRequest> action)
    {
        StartCoroutine(Request(url, action, RequestType.ASSETBUNDEL));
    }

    public void Post(string url, Action<UnityWebRequest> action, List<IMultipartFormSection> formData)
    {
        StartCoroutine(Request(url, action, RequestType.POST, formData));
    }

    IEnumerator Request(string url,Action<UnityWebRequest> action,RequestType type, List<IMultipartFormSection> formData=null)
    {
        UnityWebRequest webRequest = null;

        switch (type)
        {
            case RequestType.TEXT_GET:
                webRequest = UnityWebRequest.Get(url);
                break;
            case RequestType.TEXTUREE_GET:
                webRequest = UnityWebRequestTexture.GetTexture(url);
                break;
            case RequestType.ASSETBUNDEL:
                webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url);
                break;
            case RequestType.POST:
                webRequest = UnityWebRequest.Post(url, formData); 
                break;
            default:
                break;
        }

        if(webRequest==null)
        {
            Debug.Log("WebRequest initialise error");
            yield break;
        }

        yield return webRequest.SendWebRequest();

        action?.Invoke(webRequest);

        webRequest.Dispose();
        webRequest = null;
        Resources.UnloadUnusedAssets();
    }

    
    private void Awake()
    {
        Instance = this;        
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

1.1 Get方法调用

调用方法Get(texUrlGet, OnGetAction);

//OnGetAction回调

    void OnGetAction(UnityWebRequest webRequest)
    {
        if(webRequest.isHttpError || webRequest.isNetworkError)
        {
            Debug.Log("WebRequest error:"+webRequest.error);
            return;
        }

        //下载文本
        Debug.Log(webRequest.downloadHandler.text);

        //下载图片
        Texture2D t2d = new Texture2D(10, 10);
        t2d.LoadImage(webRequest.downloadHandler.data);

        rawImage.texture = t2d;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

1.2 调用Get方法只获取图片

GetTexture(texUrlGet, OnGetTextueAction);

    void OnGetTextueAction(UnityWebRequest webRequest)
    {
        if (webRequest.isHttpError || webRequest.isNetworkError)
        {
            Debug.Log("WebRequest error:" + webRequest.error);
            return;
        }

        DownloadHandlerTexture texHandler = (DownloadHandlerTexture)webRequest.downloadHandler;
        rawImage.texture = ((DownloadHandlerTexture)webRequest.downloadHandler).texture;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

1.3 post方法

调用方法:

        string headPath = @"D:\zzh.png";
        byte[] bytes = File.ReadAllBytes(headPath);

        List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
        formData.Add(new MultipartFormDataSection("api_key", "**********************"));
        formData.Add(new MultipartFormDataSection("api_secret", "***************************"));
        //formData.Add(new MultipartFormDataSection("image_url", texUrlGet));
        formData.Add(new MultipartFormFileSection("image_file", bytes, "zzh.png", "application/octet-stream"));

        Post("https://api-cn.faceplusplus.com/facepp/v3/detect", OnPostAction, formData);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

formData仍旧可以使用WWWForm类进行post数据添加

回调函数:

    void OnPostAction(UnityWebRequest webRequest)
    {
        if (webRequest.isHttpError || webRequest.isNetworkError)
        {
            Debug.Log("WebRequest error:" + webRequest.error);
            return;
        }

        //下载文本
        Debug.Log(webRequest.downloadHandler.text);
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

2.调整版

在post请求时根据需求分为四种模式,详细见https://www.cnblogs.com/llstart-new0201/p/6825058.html;所以此次更新增加了post模式,但新加的并未进行测试

using System.Collections;
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections.Generic;
using System.IO;

public class WebRequestUtility : MonoBehaviour
{
    public RawImage rawImage;


    public static WebRequestUtility Instance;

    enum RequestType
    {
        TEXT_GET,
        TEXTUREE_GET,
        ASSETBUNDEL,
        POST_FORM,
        POST_URLENCODED,
        POST_JSON,
        POST_XML
    }

    class PostContent
    {
        public WWWForm formData;
        public string stringContent;

        public PostContent(WWWForm formData)
        {
            this.formData = formData;
        }

        public PostContent(string text)
        {
            this.stringContent = text;
        }
    }

    public void Get(string url,Action<UnityWebRequest> action)
    {
        StartCoroutine(Request(url,action,RequestType.TEXT_GET));
    }

    public void GetTexture(string url,Action<UnityWebRequest> action)
    {
        StartCoroutine(Request(url, action, RequestType.TEXTUREE_GET));
    }

    public void GetAssetBundle(string url,Action<UnityWebRequest> action)
    {
        StartCoroutine(Request(url, action, RequestType.ASSETBUNDEL));
    }

    public void Post(string url, Action<UnityWebRequest> action, WWWForm formData)
    {
        StartCoroutine(Request(url, action, RequestType.POST_FORM, new PostContent(formData)));
    }

    public void PostUrlEncoded(string url,Action<UnityWebRequest> action,string json)
    {
        StartCoroutine(Request(url, action, RequestType.POST_URLENCODED,new PostContent(json)));
    }

    public void PostJson(string url, Action<UnityWebRequest> action, string json)
    {
        StartCoroutine(Request(url, action, RequestType.POST_JSON, new PostContent(json)));
    }

    public void PostXml(string url, Action<UnityWebRequest> action, string json)
    {
        StartCoroutine(Request(url, action, RequestType.POST_XML, new PostContent(json)));
    }

    IEnumerator Request(string url,Action<UnityWebRequest> action,RequestType type, PostContent postContent =null)
    {
        UnityWebRequest webRequest = null;

        switch (type)
        {
            case RequestType.TEXT_GET:
                webRequest = UnityWebRequest.Get(url);
                break;
            case RequestType.TEXTUREE_GET:
                webRequest = UnityWebRequestTexture.GetTexture(url);
                break;
            case RequestType.ASSETBUNDEL:
                webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url);
                break;
            case RequestType.POST_FORM:
                webRequest = UnityWebRequest.Post(url, postContent.formData); 
                break;
            case RequestType.POST_URLENCODED:
                webRequest = UnityWebRequest.Post(url, postContent.stringContent);
                //可以不进行设置,此时默认为urlencoded
                webRequest.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                break;
            case RequestType.POST_JSON:
                webRequest = UnityWebRequest.Post(url, postContent.stringContent);
                webRequest.SetRequestHeader("Content-Type", "application/json");
                break;
            case RequestType.POST_XML:
                webRequest = UnityWebRequest.Post(url, postContent.stringContent);
                webRequest.SetRequestHeader("Content-Type", "text/xml");//注:text/plain为纯文本
                break;
            default:
                break;
        }

        if(webRequest==null)
        {
            Debug.Log("WebRequest initialise error");
            yield break;
        }

        yield return webRequest.SendWebRequest();

        action?.Invoke(webRequest);

        action = null;
        webRequest.Dispose();
        webRequest = null;
        Resources.UnloadUnusedAssets();
    }

    private void Awake()
    {
        Instance = this;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133

3.Post小问题

鉴于post请求可能存在的问题,如https://www.jianshu.com/p/0f1f24829db3所述,做如下代码,

//通过PUT方式构造HTTP请求
byte[] myData = System.Text.Encoding.UTF8.GetBytes("This is some test data");
UnityWebRequest www = UnityWebRequest.Put("http://www.my-server.com/upload", myData);

//构造好后,手动将请求方式更改为POST

 www.method = UnityWebRequest.kHttpVerbPOST;

//常规的发送,接收操作

    yield return www.Send();
    if(www.isError) {
      Debug.Log(www.error);
    }
    else {
      Debug.Log("Upload complete!");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

4.UnityWebRequest LLAPI

public IEnumerator PostUrl(string url, string postData)
    {
        using (UnityWebRequest www = new UnityWebRequest(url,"POST"))
        {
            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
            www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
            www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
            www.SetRequestHeader("Content-Type", "application/json");
            yield return www.Send();
            if (www.isError)
            {
                Debug.Log(www.error);
            }
            else
            {
                // Show results as text  
                if (www.responseCode == 200)
                {
                    Debug.Log(www.downloadHandler.text);
                }
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/95751
推荐阅读
相关标签
  

闽ICP备14008679号