立项微端后,这两天开搞首包更新这块的。流程是,首包更新,对比资源md5,开线程,用webclient的downloadAysnc异步下载资源(不用downloadFile的原因是,据说比异步的慢很多)。下载过程中,发现有时候会因为文件下载不成功,导致应用挂起,不得其解。因为之前是订阅了DownloadProgressChanged,同时在对应的方法内,执行
if(e.ProgressPercentage == 100 && e.BytesReceived == e.TotalBytesToReceive)//判断是否加载完毕
估计这里不通过。查了下,这种情况,一般是因为 1是文件不存在 2.出错等原因造成的,但是都会执行委托:DownloadFileCompleted,只是此时下载的文件是0字节的,不会中断。那么订阅complete委托,在委托方法内,cancelAynsc,从而跳过该资源,继续下载其余资源,算是解决应用挂起的一个方法。但是还需要找到资源下载失败的原因。
在server上查看文件,发现文件是有的。然而console里,用try catch包裹downloadAysnc,无exception提示,然后度度了,才知道需要这样获得异常提示。代码如下;
/// <summary>
/// 下载文件
/// </summary>
void OnDownloadFile(List<object> evParams)
{
string url = evParams[0].ToString();
currDownFile = evParams[1].ToString();
using (var client = new WebClient())
{
sw.Start();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);//here
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
client.DownloadFileAsync(new System.Uri(url), currDownFile);
// wait for the download to complete
//while (client.IsBusy) { }
}
}
private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
UnityEngine.Debug.LogErrorFormat("{0}:{1}",currDownFile,e.Error.Message);
}
然后喜闻乐见的看到404错误。即使再对http协议不熟悉,到现在才发现是404,明摆着文件不存在。查了文件名:
"scene/rcc_city/city/materials/material #238.bytes",顿时明白了,是因为有了“#“特殊的符号,导致下载失败。
接着百度,url里的特殊字符参看:
http://www.cnblogs.com/panie2015/p/5885922.html,
最后,终极大法,将uri里的特殊符号转码解决,具体方法参看下面链接
转载至:http://www.cnblogs.com/dudu/archive/2011/02/25/asp_net_UrlEncode.html
例子:
var fileUrl = "scene/rcc_city/city/materials/material #238.bytes";
fileUrl = System.Uri.EscapeDataString(fileUrl);//转码
fileUrl = AppConst.WebUrl + fileUrl;
Debug.Log("download:" + fileUrl);
var localfile = Util.DataPath + "test.bytes";
BeginDownload(fileUrl, localfile);
测试通过。