当前位置:   article > 正文

Unity Best Http插件的基本使用

Unity Best Http插件的基本使用

BestHTTP/2是一个HTTP/1.1和HTTP/2实现,支持几乎所有的Unity 移动和独立平台。(官网)

2.1 Http请求

  1. 如何发送HTTP请求

Http请求类:HTTPRequest

构造函数共有 8 个:

public HTTPRequest(Uri uri);
public HTTPRequest(Uri uri, OnRequestFinishedDelegate callback);
public HTTPRequest(Uri uri, HTTPMethods methodType);
public HTTPRequest(Uri uri, bool isKeepAlive, OnRequestFinishedDelegate callback);
public HTTPRequest(Uri uri, HTTPMethods methodType, OnRequestFinishedDelegate callback);
public HTTPRequest(Uri uri, HTTPMethods methodType, bool isKeepAlive, OnRequestFinishedDelegate callback);
public HTTPRequest(Uri uri, bool isKeepAlive, bool disableCache, OnRequestFinishedDelegate callback);
public HTTPRequest(Uri uri, HTTPMethods methodType, bool isKeepAlive, bool disableCache, OnRequestFinishedDelegate callback);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

HTTPRequest参数说明:

  • uri:请求的目标 URL 或 URI。
  • methodType:指定 HTTP 请求的方法类型,例如 GET、POST、PUT 等。
  • isKeepAlive:指示是否保持与服务器的连接活动状态。如果设置为 true,则在请求完成后保持连接打开;如果设置为 false,则在每个请求完成后关闭连接。
  • disableCache:指示是否禁用缓存。如果设置为 true,则禁用缓存,确保每次请求都会从服务器获取最新的数据。
  • callback:请求完成时的回调函数,可以在其中处理响应数据。

示例:

//创建一个 get 请求,禁用缓存并在请求完成后关闭连接,接收到返回数据时将返回数据打印到控制台
HTTPRequest request = new HTTPRequest(new Uri("http://127.0.0.1/info"), HTTPMethods.Get, false, true, (request, response) => 
        { 
                Debug.Log(response.Data);
        }); 
  • 1
  • 2
  • 3
  • 4
  • 5
  1. 如何携带参数

路径参数:

路径参数直接拼接到Uri即可;

示例:

int infoId = 1;
string myUri = $"http://127.0.0.1/info/{infoId}";
HTTPRequest request = new HTTPRequest(new Uri(myUri), HTTPMethods.Get); 
  • 1
  • 2
  • 3

请求参数:

使用AddField进行添加,AddField有两个参数,参数一是fieldName,参数二是value;

示例:

HTTPRequest request = new HTTPRequest(new Uri("http://127.0.0.1/login"), HTTPMethods.Post, OnRequestFinished);
request.AddField("username", "admin");
request.AddField("password", "123456");
  • 1
  • 2
  • 3

请求头参数:

使用AddHeader进行添加请求头,和AddField类似AddHeader也是两个参数,参数一是name,参数二是value;

示例:

var request = new HTTPRequest(new Uri("http://127.0.0.1/login"), HTTPMethods.Get, OnRequestFinished);
request.AddHeader("Authorization", "mytoken");
  • 1
  • 2

请求体参数:

HTTPRequest的实例的RawData属用于存放请求体请求体

// 将JSON数据序列化为字符串
var jsonData = "{\"username\":\"admin\",\"password\":\"123456\""}";
// 将字符串编码为UTF-8字节数组
var bytes = System.Text.Encoding.UTF8.GetBytes(jsonData);
// 创建请求并将字节数组作为请求体发送
var request = new HTTPRequest(new Uri("http://127.0.0.1/login"), HTTPMethods.Post, OnRequestFinished);
request.RawData = bytes;
request.AddHeader("Content-Type", "application/json");
request.Send();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2.2 Websocket连接

  1. 创建
WebSocket webSocket = new WebSocket(new Uri("ws://127.0.0.1/webSocket")); 
  • 1
  1. 生命周期事件

OnOpen事件:在建立与服务器的连接时调用。

  • 当连接建立成功后,会触发该事件,并将WebSocket对象传递给OnWebSocketOpen方法。。

OnMessage事件:从服务器收到文本消息时调用。

  • 当从服务器接收到文本消息时,会触发该事件,并将WebSocket对象和消息内容传递给OnMessageReceived方法。

OnBinary事件:从服务器收到二进制blob消息时调用。

  • 当从服务器接收到二进制消息时,会触发该事件,并将WebSocket对象和消息字节数组传递给OnBinaryMessageReceived方法。

OnClosed事件:在客户端或服务器关闭连接时调用,或发生内部错误。

  • 当连接关闭时,会触发该事件,并将WebSocket对象、关闭代码和关闭消息传递给OnWebSocketClosed方法。

OnError事件:当无法连接到服务器、发生内部错误或连接丢失时调用。

  • 当发生错误时,会触发该事件,并将WebSocket对象和异常对象传递给OnError方法。
  1. 通信方法

Open:建立连接;

Send:发送消息到服务器;

Close:断开连接;

示例:

/// <summary>
/// websocket客户端
/// </summary>
public class WebSocketClient : SingletonManager<WebSocketClient>
{
    private static readonly object padlock = new object();
    
    /// <summary>
	/// websocket客户端实例
	/// </summary>
    protected static WebSocketClient instance;

    /// <summary>
	/// 获取单例
	/// </summary>
    public static WebSocketClient getInst()
    {
     	if (instance == null)
        {
        	lock (padlock)
            {
             	if (instance == null)
                 {
                 	instance = new WebSocketClient();
                 }
            }
        }
            return instance;
    }
    
    private WebSocket webSocket;
    /// <summary>
    /// 连接初始化
    /// </summary>
    public void init(long pid)
    {
        string url = GlobalConstant.WEBSOCKET_PATH + pid;
        webSocket = new WebSocket(new Uri(url));
        webSocket.OnOpen += OnWebSocketOpen;
        webSocket.OnMessage += OnMessageReceived;
        webSocket.OnBinary += OnBinaryMessageReceived;
        webSocket.OnClosed += OnWebSocketClosed;
        webSocket.OnError += OnError;
        webSocket.Open();
    }
    /// <summary>
    /// 服务器字符串消息
    /// </summary>
    /// <param name="webSocket"></param>
    /// <param name="message"></param>
    protected void OnMessageReceived(WebSocket webSocket, string message)
    {
        //Debug.Log("Text Message received from server: " + message);
    }
    /// <summary>
    /// 连接回调
    /// </summary>
    /// <param name="webSocket"></param>
    protected void OnWebSocketOpen(WebSocket webSocket)
    {
        Debug.Log("WebSocket Open!");
    }
    /// <summary>
    /// 服务器二进制消息
    /// </summary>
    /// <param name="webSocket"></param>
    /// <param name="message"></param>
    protected void OnBinaryMessageReceived(WebSocket webSocket, byte[] bytes)
    {
        WsResult result = ProtoBufUtil.Deserialize<WsResult>(bytes);
        if (result.status.code != 200)
        {
            Debug.Log(result.status.code);
            Debug.Log(result.status.msg);
            return;
        }
        if (result.status.code == 200)
        {
            AnalysisUtils.getProxy()[result.sendType](bytes);
        }
    }
    /// <summary>
    /// 关闭连接回调
    /// </summary>
    /// <param name="webSocket"></param>
    /// <param name="code"></param>
    /// <param name="message"></param>
    protected void OnWebSocketClosed(WebSocket webSocket, UInt16 code, string message)
    {
        Debug.Log("WebSocket Closed!");
    }
    /// <summary>
    /// 错误通知
    /// </summary>
    /// <param name="ws"></param>
    /// <param name="ex"></param>
    protected void OnError(WebSocket ws, string ex)
    {
        string errorMsg = string.Empty;
        if (ws.InternalRequest.Response != null)
        {
            errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
        }
        Debug.Log("An error occured: " + (ex != null ? ex : "Unknown: " + errorMsg));
    }
    /// <summary>
    /// 发送字符串: 
    /// </summary>
    /// <param name="msg"></param>
    public void OnSend(string msg)
    {
        webSocket.Send(msg);
    }
    /// <summary>
    /// 发送二进制流: 
    /// </summary>
    /// <param name="msg"></param>
    public void OnSend(byte[] buffer)
    {
        webSocket.Send(buffer);
    }
    /// <summary>
    /// 断开连接
    /// </summary>
    public void OnClose()
    {
        webSocket.Close();
    }
}
  • 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

上一章 【Unity DOTween插件常用方法(二)】

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探索者/article/detail/63338
推荐阅读
相关标签
  

闽ICP备14008679号