/// <summary> /// 获取网页内容 /// </summary> /// <param name="path">网页内容</param> public async Task <string> GetHtmlAsync() { string html = ""; for (int i = 1; i <= Repetitions; i++) { Init(); try { using var response = (HttpWebResponse) await Request.GetResponseAsync(); StatusCode = response.StatusCode; if (response != null && response.StatusCode == HttpStatusCode.OK) { html = GetResponseBody(response); } else if (response.StatusCode == HttpStatusCode.Moved) { string newUrl = response.Headers.GetValues("Location")[0]; jfYuRequest x = new jfYuRequest($"{newUrl}"); SetCookies = x.SetCookies; return(await x.GetHtmlAsync()); } else { return(""); } SetCookies = response.Cookies; response.Close(); break; } catch (WebException e) { if (e.Response != null) { StatusCode = ((HttpWebResponse)e.Response).StatusCode; } if (i >= Repetitions) { throw new Exception($"重复请求失败,地址:{Request.RequestUri},参数:{GetParaStr()},错误信息:{e.Message}", e); } else { await Task.Delay(5000); } } catch (Exception ex) { if (i >= Repetitions) { throw new Exception($"重复请求失败,地址:{Request.RequestUri},参数:{GetParaStr()},错误信息:{ex.Message}", ex); } else { await Task.Delay(5000); } } } return(html); }
public async Task <bool> GetFileAsync(string path, Action <decimal, decimal, decimal> setProgress = null) { Init(); HttpWebResponse response; try { response = (HttpWebResponse)(await Request.GetResponseAsync()); StatusCode = response.StatusCode; } catch (WebException e) { StatusCode = ((HttpWebResponse)e.Response).StatusCode; return(false); } if (response != null && response.StatusCode == HttpStatusCode.OK) { using Stream responseStream = response.GetResponseStream(); //文件大小 var FileSize = decimal.Parse(response.ContentLength.ToString()); //下载进度 decimal Progress = 0M; //下载速度KB/s decimal Speed = 0M; //剩余时间/秒 decimal Remain = 0; //下载文件块大小,后期可通过此次进行速度限制 byte[] buffer = new byte[4096]; try { using (FileStream fs = File.Create(path)) { //开启计时 long LastSaveSize = 0; var t = new System.Timers.Timer(1000) { AutoReset = true, Enabled = true }; t.Elapsed += (s, e) => { LastSaveSize = fs.Length; setProgress?.Invoke(Progress, Speed, Remain); }; t.Start(); int bytesRead; do { bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length); await fs.WriteAsync(buffer, 0, bytesRead); //计算进度 Progress = fs.Length / FileSize * 100; //计算速度 Speed = (decimal)(fs.Length - LastSaveSize) / 1024; //剩余时间 Remain = Speed == 0 ? 0 : (FileSize - fs.Length) / (Speed * 1024); }while (bytesRead > 0); fs.Flush(); t.Stop(); setProgress?.Invoke(100M, 0M, 0M); } if (File.Exists(path) && new FileInfo(path).Length == FileSize) { return(true); } else { return(false); } } catch (Exception ex) { throw new Exception("下载文件出错", ex); } } else if (response.StatusCode == HttpStatusCode.Moved) { string newUrl = response.Headers.GetValues("Location")[0]; jfYuRequest x = new jfYuRequest($"{newUrl}"); return(await x.GetFileAsync(path, setProgress)); } else { return(false); } }