/// <summary> /// 从 HttpClientFactory 的唯一名称中获取 HttpClient 对象,并加载到 SenparcHttpClient 中 /// </summary> /// <param name="httpClientName"></param> /// <returns></returns> public static SenparcHttpClient GetInstanceByName(string httpClientName) { if (!string.IsNullOrEmpty(httpClientName)) { var clientFactory = SenparcDI.GetRequiredService <IHttpClientFactory>(); var httpClient = clientFactory.CreateClient(httpClientName); return(new SenparcHttpClient(httpClient)); } return(SenparcDI.GetRequiredService <SenparcHttpClient>(true)); }
/// <summary> /// 使用Get方法获取字符串结果(没有加入Cookie) /// </summary> /// <param name="url"></param> /// <returns></returns> public static string HttpGet(string url, Encoding encoding = null) { #if NET35 || NET40 || NET45 WebClient wc = new WebClient(); wc.Proxy = _webproxy; wc.Encoding = encoding ?? Encoding.UTF8; return(wc.DownloadString(url)); #else var handler = HttpClientHelper.GetHttpClientHandler(null, SenparcHttpClientWebProxy, DecompressionMethods.GZip); HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; return(httpClient.GetStringAsync(url).Result); #endif }
/// <summary> /// .NET Core 版本的HttpWebRequest参数设置 /// </summary> /// <returns></returns> private static HttpClient HttpGet_Common_NetCore(string url, CookieContainer cookieContainer = null, Encoding encoding = null, X509Certificate2 cer = null, string refererUrl = null, bool useAjax = false, int timeOut = Config.TIME_OUT) { var handler = HttpClientHelper.GetHttpClientHandler(cookieContainer, RequestUtility.SenparcHttpClientWebProxy, DecompressionMethods.GZip); if (cer != null) { handler.ClientCertificates.Add(cer); } HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; HttpClientHeader(httpClient, refererUrl, useAjax, null, timeOut); return(httpClient); }
/// <summary> /// 【异步方法】使用Post方法上传数据并下载文件或结果 /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <param name="stream"></param> public static async Task DownloadAsync(string url, string data, Stream stream) { #if NET35 || NET40 || NET45 WebClient wc = new WebClient(); var fileBytes = await wc.UploadDataTaskAsync(url, "POST", Encoding.UTF8.GetBytes(string.IsNullOrEmpty(data) ? "" : data)).ConfigureAwait(false); await stream.WriteAsync(fileBytes, 0, fileBytes.Length).ConfigureAwait(false);//也可以分段写入 #else HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; HttpContent hc = new StringContent(data); var ht = await httpClient.PostAsync(url, hc).ConfigureAwait(false); var fileBytes = await ht.Content.ReadAsByteArrayAsync().ConfigureAwait(false); await stream.WriteAsync(fileBytes, 0, fileBytes.Length).ConfigureAwait(false);//也可以分段写入 #endif }
/// <summary> /// 使用Get方法获取字符串结果(没有加入Cookie) /// </summary> /// <param name="url"></param> /// <returns></returns> public static async Task <string> HttpGetAsync(string url, Encoding encoding = null) { #if NET35 || NET40 || NET45 WebClient wc = new WebClient(); wc.Proxy = _webproxy; wc.Encoding = encoding ?? Encoding.UTF8; return(await wc.DownloadStringTaskAsync(url).ConfigureAwait(false)); #else var handler = new HttpClientHandler { UseProxy = SenparcHttpClientWebProxy != null, Proxy = SenparcHttpClientWebProxy, }; HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; return(await httpClient.GetStringAsync(url).ConfigureAwait(false)); #endif }
/// <summary> /// 【异步方法】从Url下载,并保存到指定目录 /// </summary> /// <param name="url">需要下载文件的Url</param> /// <param name="filePathName">保存文件的路径,如果下载文件包含文件名,按照文件名储存,否则将分配Ticks随机文件名</param> /// <param name="timeOut">超时时间</param> /// <returns></returns> public static async Task <string> DownloadAsync(string url, string filePathName, int timeOut = Config.TIME_OUT) { var dir = Path.GetDirectoryName(filePathName) ?? "/"; Directory.CreateDirectory(dir); #if NET45 System.Net.Http.HttpClient httpClient = new HttpClient(); #else System.Net.Http.HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; #endif httpClient.Timeout = TimeSpan.FromMilliseconds(timeOut); using (var responseMessage = await httpClient.GetAsync(url).ConfigureAwait(false)) { if (responseMessage.StatusCode == HttpStatusCode.OK) { string responseFileName = null; //ContentDisposition可能会为Null if (responseMessage.Content.Headers.ContentDisposition != null && responseMessage.Content.Headers.ContentDisposition.FileName != null && responseMessage.Content.Headers.ContentDisposition.FileName != "\"\"") { responseFileName = Path.Combine(dir, responseMessage.Content.Headers.ContentDisposition.FileName.Trim('"')); } var fullName = responseFileName ?? Path.Combine(dir, GetRandomFileName()); using (var fs = File.Open(fullName, FileMode.Create)) { using (var responseStream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false)) { await responseStream.CopyToAsync(fs).ConfigureAwait(false); await fs.FlushAsync().ConfigureAwait(false); } } return(fullName); } else { return(null); } } }
/// <summary> /// 从Url下载 /// </summary> /// <param name="url"></param> /// <param name="stream"></param> public static void Download(string url, Stream stream) { #if NET35 || NET40 || NET45 //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); WebClient wc = new WebClient(); var data = wc.DownloadData(url); stream.Write(data, 0, data.Length); //foreach (var b in data) //{ // stream.WriteByte(b); //} #else HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; var t = httpClient.GetByteArrayAsync(url); t.Wait(); var data = t.Result; stream.Write(data, 0, data.Length); #endif }
/// <summary> /// 【异步方法】异步从Url下载 /// </summary> /// <param name="url"></param> /// <param name="stream"></param> /// <returns></returns> public static async Task DownloadAsync(string url, Stream stream) { #if NET35 || NET40 || NET45 //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); WebClient wc = new WebClient(); var data = await wc.DownloadDataTaskAsync(url).ConfigureAwait(false); await stream.WriteAsync(data, 0, data.Length).ConfigureAwait(false); //foreach (var b in data) //{ // stream.WriteAsync(b); //} #else HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; var data = await httpClient.GetByteArrayAsync(url).ConfigureAwait(false); await stream.WriteAsync(data, 0, data.Length).ConfigureAwait(false); #endif }
/// <summary> /// 使用Post方法上传数据并下载文件或结果 /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <param name="stream"></param> public static void Download(string url, string data, Stream stream) { #if NET35 || NET40 || NET45 WebClient wc = new WebClient(); var file = wc.UploadData(url, "POST", Encoding.UTF8.GetBytes(string.IsNullOrEmpty(data) ? "" : data)); stream.Write(file, 0, file.Length); //foreach (var b in file) //{ // stream.WriteByte(b); //} #else HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; HttpContent hc = new StringContent(data); var ht = httpClient.PostAsync(url, hc); ht.Wait(); var ft = ht.Result.Content.ReadAsByteArrayAsync(); ft.Wait(); var file = ft.Result; stream.Write(file, 0, file.Length); #endif }
//#if !NET35 && !NET40 /// <summary> /// 从Url下载,并保存到指定目录 /// </summary> /// <param name="url">需要下载文件的Url</param> /// <param name="filePathName">保存文件的路径,如果下载文件包含文件名,按照文件名储存,否则将分配Ticks随机文件名</param> /// <param name="timeOut">超时时间</param> /// <returns></returns> public static string Download(string url, string filePathName, int timeOut = 999) { var dir = Path.GetDirectoryName(filePathName) ?? "/"; Directory.CreateDirectory(dir); #if NET35 || NET40 || NET45 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Timeout = timeOut; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { string responseFileName = null; var contentDescriptionHeader = response.GetResponseHeader("Content-Disposition"); if (!string.IsNullOrEmpty(contentDescriptionHeader)) { var fileName = Regex.Match(contentDescriptionHeader, @"(?<=filename="")([\s\S]+)(?= "")", RegexOptions.IgnoreCase).Value; responseFileName = Path.Combine(dir, fileName); } var fullName = responseFileName ?? Path.Combine(dir, GetRandomFileName()); using (var fs = File.Open(filePathName, FileMode.OpenOrCreate)) { byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { fs.Write(bArr, 0, size); fs.Flush(); size = responseStream.Read(bArr, 0, (int)bArr.Length); } } return(fullName); } #else System.Net.Http.HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; using (var responseMessage = httpClient.GetAsync(url).Result) { if (responseMessage.StatusCode == HttpStatusCode.OK) { string responseFileName = null; //ContentDisposition可能会为Null if (responseMessage.Content.Headers.ContentDisposition != null && responseMessage.Content.Headers.ContentDisposition.FileName != null && responseMessage.Content.Headers.ContentDisposition.FileName != "\"\"") { responseFileName = Path.Combine(dir, responseMessage.Content.Headers.ContentDisposition.FileName.Trim('"')); } var fullName = responseFileName ?? Path.Combine(dir, GetRandomFileName()); using (var fs = File.Open(fullName, FileMode.Create)) { using (var responseStream = responseMessage.Content.ReadAsStreamAsync().Result) { responseStream.CopyTo(fs); fs.Flush(); } } return(fullName); } else { return(null); } } #endif }
/// <summary> /// 给.NET Core使用的HttpPost请求公共设置方法 /// </summary> /// <param name="url"></param> /// <param name="hc"></param> /// <param name="cookieContainer"></param> /// <param name="postStream"></param> /// <param name="fileDictionary"></param> /// <param name="refererUrl"></param> /// <param name="encoding"></param> /// <param name="cer"></param> /// <param name="useAjax"></param> /// <param name="headerAddition">header附加信息</param> /// <param name="timeOut"></param> /// <param name="checkValidationResult"></param> /// <param name="contentType"></param> /// <returns></returns> public static HttpClient HttpPost_Common_NetCore(string url, out HttpContent hc, CookieContainer cookieContainer = null, Stream postStream = null, Dictionary <string, string> fileDictionary = null, string refererUrl = null, Encoding encoding = null, X509Certificate2 cer = null, bool useAjax = false, Dictionary <string, string> headerAddition = null, int timeOut = Config.TIME_OUT, bool checkValidationResult = false, string contentType = HttpClientHelper.DEFAULT_CONTENT_TYPE) { HttpClientHandler handler = HttpClientHelper.GetHttpClientHandler(cookieContainer, SenparcHttpClientWebProxy, DecompressionMethods.GZip); if (checkValidationResult) { handler.ServerCertificateCustomValidationCallback = new Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>(CheckValidationResult); } if (cer != null) { handler.ClientCertificates.Add(cer); } var senparcHttpClient = SenparcDI.GetRequiredService <SenparcHttpClient>(); senparcHttpClient.SetCookie(new Uri(url), cookieContainer);//设置Cookie HttpClient client = senparcHttpClient.Client; HttpClientHeader(client, refererUrl, useAjax, headerAddition, timeOut); #region 处理Form表单文件上传 var formUploadFile = fileDictionary != null && fileDictionary.Count > 0;//是否用Form上传文件 if (formUploadFile) { contentType = "multipart/form-data"; //通过表单上传文件 string boundary = "----" + SystemTime.Now.Ticks.ToString("x"); var multipartFormDataContent = new MultipartFormDataContent(boundary); hc = multipartFormDataContent; foreach (var file in fileDictionary) { try { var fileName = file.Value; //准备文件流 using (var fileStream = FileHelper.GetFileStream(fileName)) { if (fileStream != null) { //存在文件 var memoryStream = new MemoryStream(); fileStream.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); //multipartFormDataContent.Add(new StreamContent(memoryStream), file.Key, Path.GetFileName(fileName)); //报流已关闭的异常 multipartFormDataContent.Add(CreateFileContent(memoryStream, file.Key, Path.GetFileName(fileName)), file.Key, Path.GetFileName(fileName)); fileStream.Dispose(); } else { //不存在文件或只是注释 multipartFormDataContent.Add(new StringContent(file.Value), "\"" + file.Key + "\""); } } } catch (Exception ex) { throw ex; } } hc.Headers.ContentType = MediaTypeHeaderValue.Parse(string.Format("multipart/form-data; boundary={0}", boundary)); } else { if (postStream.Length > 0) { if (contentType == HttpClientHelper.DEFAULT_CONTENT_TYPE) { //如果ContentType是默认值,则设置成为二进制流 contentType = "application/octet-stream"; } //contentType = "application/x-www-form-urlencoded"; } hc = new StreamContent(postStream); hc.Headers.ContentType = new MediaTypeHeaderValue(contentType); //使用Url格式Form表单Post提交的时候才使用application/x-www-form-urlencoded //去掉注释以测试Request.Body为空的情况 //hc.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); } //HttpContentHeader(hc, timeOut); #endregion if (!string.IsNullOrEmpty(refererUrl)) { client.DefaultRequestHeaders.Referrer = new Uri(refererUrl); } return(client); }