Unity SKFramework框架(七)、WebRequester 网络请求模块

目录

一、WebInterface Profile 网络接口配置文件

1.创建网络接口配置文件

2.配置网络接口配置文件

3.配置文件的Resources资源路径

二、WebRequester 网络请求管理器

1.注册接口

2.回调函数

3.发起请求

4.注销接口

三、补充说明

1.GET

2.POST


一、WebInterface Profile 网络接口配置文件

1.创建网络接口配置文件

2.配置网络接口配置文件

在网上找了一个获取当前日期和时间的接口,我们以它为例,配置网络接口配置文件:

Name表示该接口的命名,Url为接口的地址,Method表示该接口的请求方式,该接口以GET方式调用,Args为string类型数组,表示接口的参数名称,该接口不包含任何参数,所以不需要添加。

3.配置文件的Resources资源路径

模块管理器初始化时默认以WebInterface Profile为资源路径进行配置文件的加载:

//加载网络接口配置文件
Resources.Load<WebInterfaceProfile>("WebInterface Profile")

二、WebRequester 网络请求管理器

1.注册接口

using UnityEngine;
using SK.Framework;

public class Example : MonoBehaviour
{
    private void Start()
    {
        //注册接口
        WebRequester.RegisterInterface<TextResponseWebInterface>("北京时间", out var time);
    }
}

2.回调函数

通过OnCompleted设置回调函数:

//设置回调函数
time.OnCompleted(s => Debug.Log(s));

3.发起请求

//发起网络请求
time.SendWebRequest();

或者

//发起网络请求
WebRequester.SendWebRequest("北京时间");

4.注销接口

传入接口名称进行注销:

//注销接口
WebRequester.UnregisterInterface("北京时间");

三、补充说明

1.GET

        上例中我们以GET的方式发起网络请求调用一个接口,并且没有任何参数,假如接口包含参数arg1和arg2,我们需要在配置文件中进行设置:

在发起请求时需要传入参数的值:

//发起网络请求
time.SendWebRequest("value1", "value2");

此时系统会自动将Url进行参数拼接,最终结果为:

apps.game.qq.com/CommArticle/app/reg/gdate.php?arg1=value1&arg2=value2

2.POST

        倘若以POST方式发起网络请求调用接口,传入的第一个参数是POST的数据,后面的参数表示请求头,为可选参数。以实际项目中的一个接口为例:

        如图所示,接口请求方式为POST,请求头需要设置"Content-Type" "application/json",POST的数据是如下结构的JSON内容:

[Serializable]
public class HourStatisticsRequest
{
    /// <summary>
    /// 日期 格式20200426
    /// </summary>
    public string day;
    /// <summary>
    /// 类型 1温度
    /// </summary>
    public int type;

    public HourStatisticsRequest()
    {
        day = string.Format("{0:yyyyMMdd}", DateTime.Now);
        type = 1;
    }
    public HourStatisticsRequest(string day, int type)
    {
        this.day = day;
        this.type = type;
    }
}

配置文件:

注册和调用接口:

using UnityEngine;
using SK.Framework;

public class Example : MonoBehaviour
{
    private void Start()
    {
        //注册接口
        WebRequester.RegisterInterface<TextResponseWebInterface>("环境气体数据监测统计", out var hourStatistics);
        //设置回调函数
        hourStatistics.OnCompleted(response => Debug.Log(response));
        //发起请求
        hourStatistics.SendWebRequest(JsonUtility.ToJson(new HourStatisticsRequest()), RequestHeader.CONTENTTYPE_APPLICATIONJSON);
    }
}

如上所示,请求头的键值以=号进行拼接。

猜你喜欢

转载自blog.csdn.net/qq_42139931/article/details/124808861