上篇文章介绍完了Http协议种请求下载资源的方式,现在需要测试。关于本地搭建服务器,读者可以查看本人写的另外一篇博客Tomcat服务器。
测试类HttpTest
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
/*
* Author:W
* http协议请求下载测试
*/
namespace W.GameFramework.HotUpdate
{
public class HttpTest : MonoBehaviour
{
private string url = "http://localhost:8080/download/nguichajian.zip";
//C:/Users/lunqiang.wang/Desktop/UnityHot2/UnityHotFix-master/Assets
private string rootPath;
private string filePath;
private HttpHelper httpHelper = null;
public Button newDownloadBtn;
public Button continueDownloadBtn;
public Button newDownloadBtn2;
public Button continueDownloadBtn2;
// Use this for initialization
void Start()
{
newDownloadBtn.onClick.AddListener(OnNewDownloadBtnClick);
continueDownloadBtn.onClick.AddListener(OnContinueDownloadBtnClick);
newDownloadBtn2.onClick.AddListener(OnNewDownloadBtnClick2);
continueDownloadBtn2.onClick.AddListener(OnContinueDownloadBtnClick2);
rootPath = Application.dataPath.Replace("Assets", "") + "download";
if (!Directory.Exists(rootPath))
Directory.CreateDirectory(rootPath);
filePath = rootPath + "/nguichajian.zip";
}
void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
//模拟中途暂停下载
if(httpHelper!=null)
httpHelper.IsStop = true;
}
}
private void OnNewDownloadBtnClick()
{
Debug.Log("=======HttpWebRequest 完全下载============");
httpHelper = new HttpWebRequestHelper();
httpHelper.SendHttpRequest(url, filePath, DownloadType.New, OnDownLoadBeginHandler, OnDownloadEndHandler,
OnDownloadProgressHandler, OnDownloadErrorHandler);
}
private void OnContinueDownloadBtnClick()
{
Debug.Log("=======HttpWebRequest 断点续传下载============");
httpHelper = new HttpWebRequestHelper();
httpHelper.SendHttpRequest(url, filePath, DownloadType.Continue, OnDownLoadBeginHandler, OnDownloadEndHandler,
OnDownloadProgressHandler, OnDownloadErrorHandler);
}
private void OnNewDownloadBtnClick2()
{
Debug.Log("=======UnityWebRequest 完全下载============");
httpHelper = new UnityWebHttpRequestHelper();
httpHelper.SendHttpRequest(url, filePath, DownloadType.New, OnDownLoadBeginHandler, OnDownloadEndHandler,
OnDownloadProgressHandler, OnDownloadErrorHandler);
}
private void OnContinueDownloadBtnClick2()
{
Debug.Log("=======UnityWebRequest 断点续传下载============");
httpHelper = new UnityWebHttpRequestHelper();
httpHelper.SendHttpRequest(url, filePath, DownloadType.Continue, OnDownLoadBeginHandler, OnDownloadEndHandler,
OnDownloadProgressHandler, OnDownloadErrorHandler);
}
private void OnDownLoadBeginHandler()
{
Debug.Log("资源:"+httpHelper.url+" 开始下载!");
}
private void OnDownloadEndHandler()
{
Debug.Log("资源:" + httpHelper.url+" 下载完成,保存路径:"+httpHelper.path);
}
private void OnDownloadProgressHandler(float progress)
{
Debug.Log("资源:" + httpHelper.url+" 当前进度==="+progress);
}
private void OnDownloadErrorHandler(string errorCode)
{
Debug.LogError("资源:"+url+" 下载错误error="+errorCode);
}
}
}
测试UI如下
模拟测试结果如下
HttpWebRequest接口测试结果
UnityWebRequest接口测试结果
?至此关于Unity实现Http协议请求加载2种实现方式已经完成!供大家交流借鉴。
|