Ejemplo n.º 1
0
        private async Task <(byte[], CacheControlHeaderValue)> CreateDownloadTask(ILoadingContext <TSource> context, Uri uri, CancellationToken cancellationToken)
        {
            var client = _httpClientFactory.CreateClient(Constants.HttpClientName);

            using var response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken);

            response.EnsureSuccessStatusCode();

            var cacheControl  = response.Headers.CacheControl;
            var contentLength = response.Content.Headers.ContentLength;

            using var stream = await response.Content.ReadAsStreamAsync();

            var buffer = new byte[BufferSize];
            int bytesRead;
            var bytes = new List <byte>();

            var downloadProgress = new HttpDownloadProgress();

            if (contentLength.HasValue)
            {
                downloadProgress.TotalBytesToReceive = (ulong)contentLength.Value;
            }

            context.RaiseDownloadProgressChanged(downloadProgress);

            while ((bytesRead = await stream.ReadAsync(buffer, 0, BufferSize, cancellationToken)) > 0)
            {
                bytes.AddRange(buffer.Take(bytesRead));
                downloadProgress.BytesReceived += (ulong)bytesRead;
                context.RaiseDownloadProgressChanged(downloadProgress);
            }

            return(bytes.ToArray(), cacheControl);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// HTTP下载性能优先
        /// </summary>
        /// <param name="url">下载地址</param>
        /// <param name="fileName">保存本地路劲</param>
        /// <param name="progress">进度的委托事件</param>
        public void Download(string url, string fileName, HttpDownloadProgress progress)
        {
            RequestBuilder request = Http.Get(url).DownloadTo(fileName, onProgressChanged: (bytesCopied, totalBytes) => {
                progress(bytesCopied, totalBytes, HttpDownloadState.Loading, null);
            },
                                                              onSuccess: (headers) => {
                progress(0, 0, HttpDownloadState.Success, null);
            });

            request.OnFail(action => {
                progress(0, 0, HttpDownloadState.ERROR, action.Message);//这里发生错误异常
            }).Go();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// HTTP多线程下载,急速提升下载速度,但很消耗性能
        /// </summary>
        /// <param name="url">下载地址</param>
        /// <param name="fileName">保存本地路劲</param>
        /// <param name="ThreadNum">线程数量(建议6个)</param>
        /// <param name="progress"></param>
        public void DownloadMutilThread(string url, string fileName, int threadNum, int bufSize, HttpDownloadProgress progress)
        {
            HttpMutilThreadDownload httpMTD = new HttpMutilThreadDownload(url, fileName, threadNum, bufSize, progress);

            httpMTD.StartDownload();
        }