Ejemplo n.º 1
0
        /// <summary>
        /// 启动下载
        /// </summary>
        /// <param name="sUrl">下载链接</param>
        /// <param name="sPath">路径文件名</param>
        /// <param name="data">中间传递的数据</param>
        /// <param name="UpdateFunc">进度更新</param>
        /// <param name="CompleteFunc">下载结束</param>
        /// <param name="ErrFunc">错误</param>
        /// <param name="Timeout">超时</param>
        /// <param name="UserAgent"></param>
        /// <param name="ContentType"></param>
        public static Task <object> StartAsync(string sUrl,
                                               string sPath,
                                               object data = null,
                                               UpdateDownloadNotify UpdateFunc     = null,
                                               CompleteDownloadNotify CompleteFunc = null,
                                               ErrDownloadNotify ErrFunc           = null,
                                               int RetryNum               = 0,
                                               int Timeout                = 5 * 1000,
                                               string UserAgent           = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
                                               string ContentType         = "application/x-www-form-urlencoded; charset=UTF-8",
                                               bool bOnlyGetSize          = false,
                                               bool bAppendFile           = false,
                                               HttpHelper.ProxyInfo Proxy = null)
        {
            return(Task.Run(() =>
            {
                UpdateDownloadNotify UpdateMothed = UpdateFunc == null ? null : new UpdateDownloadNotify(UpdateFunc);
                CompleteDownloadNotify CompleteMothed = CompleteFunc == null ? null : new CompleteDownloadNotify(CompleteFunc);
                ErrDownloadNotify ErrMothed = ErrFunc == null ? null : new ErrDownloadNotify(ErrFunc);
                long lAlreadyDownloadSize = 0;
                long lTotalSize = 0;
                long lIncreSize = 0;

                if (RetryNum > 50)
                {
                    RetryNum = 50;
                }

                RETRY_ENTRY:
                try
                {
                    bool bRet = false;
                    ServicePointManager.Expect100Continue = false;

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sUrl);
                    request.Method = "GET";
                    request.ContentType = ContentType;
                    request.Timeout = Timeout;
                    //request.KeepAlive       = true;
                    request.UserAgent = UserAgent;
                    request.Proxy = null;

                    if (Proxy != null && Proxy.Host.IsNotBlank() && Proxy.Port >= 0)
                    {
                        WebProxy myProxy = new WebProxy(Proxy.Host, Proxy.Port);
                        if (Proxy.Username.IsNotBlank() && Proxy.Password.IsNotBlank())
                        {
                            myProxy.Credentials = new NetworkCredential(Proxy.Username, Proxy.Password);
                        }

                        request.Proxy = myProxy;
                        request.Credentials = CredentialCache.DefaultNetworkCredentials;
                    }

                    //开始请求
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    lTotalSize = response.ContentLength;
                    if (bOnlyGetSize)
                    {
                        return (object)lTotalSize;
                    }

                    //创建目录
                    string pDir = Path.GetDirectoryName(sPath);
                    PathHelper.Mkdirs(pDir);

                    if (File.Exists(sPath) && !bAppendFile)
                    {
                        File.Delete(sPath);
                    }

                    //打开文件
                    Stream myResponseStream = response.GetResponseStream();
                    //一分钟超时
                    myResponseStream.ReadTimeout = 60000;
                    System.IO.Stream pFD = new System.IO.FileStream(sPath, bAppendFile ? System.IO.FileMode.Append : System.IO.FileMode.Create);

                    //如果走到这里的话,就不能重试了,要不如进度会出错
                    RetryNum = 0;
                    byte[] buf = new byte[1024];
                    int size = 0;
                    while ((size = myResponseStream.Read(buf, 0, (int)buf.Length)) > 0)
                    {
                        lIncreSize = size;
                        lAlreadyDownloadSize += size;
                        pFD.Write(buf, 0, size);
                        if (UpdateFunc != null)
                        {
                            if (!UpdateMothed(lTotalSize, lAlreadyDownloadSize, lIncreSize, data))
                            {
                                goto RETURN_POINT;
                            }
                        }
                    }

                    if (CompleteMothed != null)
                    {
                        CompleteMothed(lTotalSize, data);
                    }
                    bRet = true;

                    RETURN_POINT:
                    pFD.Close();
                    myResponseStream.Close();
                    return bRet;
                }
                catch (System.Exception e)
                {
                    if (RetryNum > 0)
                    {
                        RetryNum--;
                        goto RETRY_ENTRY;
                    }

                    if (ErrMothed != null)
                    {
                        ErrMothed(lTotalSize, lAlreadyDownloadSize, e.Message, data);
                    }
                    if (bOnlyGetSize)
                    {
                        return (object)0;
                    }
                    return (object)false;
                }
            }));
        }