封装WWW类

第一个脚本WWW中心

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WWWHelper : MonoBehaviour
{
    public static WWWHelper Instance;
    private void Awake()
    {
        Instance = this;
    }

    Queue<WWWItem> downQueue = new Queue<WWWItem>();
    bool isDownLoadFinished = true;
    /// <summary>
    /// 加入下载任务
    /// </summary>
    /// <param name="item"></param>
    public void AddTask(WWWItem item)
    {
        downQueue.Enqueue(item);
        if (downQueue.Count == 1 && isDownLoadFinished)
        {
            isDownLoadFinished = false;
            StartCoroutine(DownLoad());
        }
    }
    /// <summary>
    /// 下载后取消任务
    /// </summary>
    /// <returns></returns>
    public IEnumerator DownLoad()
    {
        while (downQueue.Count > 0)
        {
            WWWItem item = downQueue.Dequeue();
            yield return item.DownLoad();
        }
        isDownLoadFinished = true;
    }
}
第二个脚本抽象下载Item

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WWWItem {
    /// <summary>
    /// 开始下载
    /// </summary>
    public virtual void BeginDownLoad()
    {

    }
    /// <summary>
    /// 下载完成
    /// </summary>
    /// <param name="www"></param>
    public virtual void DownLoadFinish(WWW www)
    {

    }
    /// <summary>
    /// 下载出错
    /// </summary>
    /// <param name="tempItem"></param>
    public virtual void DownLoadError(WWWItem tempItem)
    {

    }
    private string url;
    public string URL
    {
        get { return url; }
        set { url = value; }
    }
    public IEnumerator DownLoad()
    {
        BeginDownLoad();
        WWW www = new WWW(URL);
        yield return www;
        if (string.IsNullOrEmpty(www.error))
        {
            DownLoadFinish(www);
        }
        else
        {
            DownLoadError(this);
        }
    }
}
第三个脚本构造下载元素

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WWWTxt : WWWItem {

    /// <summary>
    /// 构造方法
    /// </summary>
    /// <param name="path">传递相对路径</param>
    public WWWTxt(string path)
    {
        path = Application.dataPath+path;
        InitPath(path);
    }
    public override void DownLoadError(WWWItem tempItem)
    {
        WWWHelper.Instance.AddTask(tempItem);
    }
    public override void DownLoadFinish(WWW www)
    {
        Debug.Log("Process Txt==" + www.text);
    }
    /// <summary>
    /// 初始化路径
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public void InitPath(string url)
    {
        if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
        {
            this.URL = "file:///" + url;
        }
        else if (Application.platform == RuntimePlatform.Android)
        {
            this.URL = "jar:file://" + url;
        }
        else
        {
            this.URL = "file://" + url;
        }
    }
}
第四个脚本使用www

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UseWWW : MonoBehaviour {


    void Update () {
        if (Input.GetKeyDown(KeyCode.A))
        {
            WWWTxt tempItem = new WWWTxt("/test.xml");
            WWWHelper.Instance.AddTask(tempItem);
        }
    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 以下是一个简单的Python异步HTTP请求封装示例: ```python import asyncio import aiohttp class AsyncHttpRequest: def __init__(self, headers=None, timeout=None): self.headers = headers self.timeout = timeout async def get(self, url, params=None): async with aiohttp.ClientSession(headers=self.headers, timeout=self.timeout) as session: async with session.get(url, params=params) as response: return await response.text() async def post(self, url, data=None, json=None): async with aiohttp.ClientSession(headers=self.headers, timeout=self.timeout) as session: async with session.post(url, data=data, json=json) as response: return await response.text() ``` 该使用Python的asyncio库和aiohttp库来实现异步HTTP请求。它具有get和post方法来执行GET和POST请求。可以通过headers和timeout参数设置请求的头信息和超时时间。 在调用该时,可以使用await关键字来等待请求返回结果,如下所示: ```python async def main(): request = AsyncHttpRequest(headers={'User-Agent': 'Mozilla/5.0'}, timeout=10) response = await request.get('https://www.example.com') print(response) asyncio.run(main()) ``` 在此示例中,创建了一个AsyncHttpRequest对象,并使用get方法执行了一个GET请求。使用await关键字等待请求返回结果后,将响应文本打印到控制台上。 ### 回答2: Python中可以使用第三方库asyncio和aiohttp来封装异步http请求。 首先,我们需要导入相应的库: ```python import asyncio import aiohttp ``` 然后,我们可以定义一个异步http请求,如下所示: ```python class AsyncHttpRequest: def __init__(self): self.session = aiohttp.ClientSession() async def request(self, method, url, headers=None, params=None, data=None): async with self.session.request(method, url, headers=headers, params=params, data=data) as response: return await response.text() async def close(self): await self.session.close() ``` 在的初始化方法中,我们创建了一个aiohttp的ClientSession对象用于发送http请求。然后,定义了一个request方法来发送http请求并返回响应结果。在请求方法中,我们使用async with语句来发送请求,并使用asyncio库的await方法等待响应结果。最后,我们定义了一个close方法来关闭http请求的会话。 使用该异步http请求的例子如下: ```python async def main(): async_http_request = AsyncHttpRequest() response = await async_http_request.request('GET', 'https://www.example.com') print(response) await async_http_request.close() asyncio.run(main()) ``` 在主函数main中,我们创建了AsyncHttpRequest对象,并调用request方法发送了一个GET请求并获取了响应结果。最后,我们调用close方法关闭了http请求的会话。 以上就是使用asyncio和aiohttp封装异步http请求的简单示例。通过异步http请求,我们可以方便地发送异步请求并处理响应结果。 ### 回答3: Python中有多种方式可以封装异步http请求,如使用asyncio库、aiohttp库等。这里以aiohttp为例进行说明。 首先,我们可以定义一个HttpClient封装异步http请求的功能。该需要引入aiohttp库并使用async关键字来定义异步函数。 首先,在的初始化方法中,我们可以创建一个aiohttp的ClientSession对象作为的成员变量,以便在整个中进行http请求。 接下来,我们可以定义一个异步的GET请求方法,该方法接收一个url参数,并使用aiohttp库的get方法来发送异步的GET请求。我们可以使用await关键字来等待该请求的响应并返回结果。 然后,我们可以定义一个异步的POST请求方法,该方法接收一个url和data参数,使用aiohttp库的post方法来发送异步的POST请求。同样,我们也使用await关键字来等待该请求的响应并返回结果。 最后,我们需要在HttpClient中定义一个关闭方法,用于在使用完毕后关闭aiohttp的ClientSession对象,以释放资源。 总结来说,封装异步http请求主要包括以下步骤: 1. 引入aiohttp库和其他必要的库; 2. 创建并初始化的成员变量; 3. 定义异步的GET请求方法,接收url参数,使用aiohttp库发送异步GET请求并等待响应; 4. 定义异步的POST请求方法,接收url和data参数,使用aiohttp库发送异步POST请求并等待响应; 5. 定义关闭方法,用于关闭aiohttp的ClientSession对象。 通过以上步骤,我们可以封装一个简单的异步http请求,方便在Python中进行异步http请求的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值