/// <summary> /// HttpWebRequest 用GET方法访问指定URI /// </summary> public static T HttpGet <T>(string uri, IDictionary <string, string> headers, string contentType, WebProxy proxy) { StreamReader reader = null; Stream stream = null; try { stream = HttpGet(uri, headers, contentType, proxy); reader = new StreamReader(stream); string line = reader.ReadToEnd(); if (typeof(T) == typeof(string)) { return((T)(line as object)); } T value = SerializeHelper.DeserializeFromJson <T>(line); return(value); } catch (WebException we) { WebHelper.ThrowWebException(we); throw; } finally { if (stream != null) { stream.Close(); } if (reader != null) { reader.Close(); } } }
/// <summary> /// HttpClient 用POST方法访问指定URI /// </summary> /// <typeparam name="T"></typeparam> /// <param name="uri">请求发送到的 URI。</param> /// <param name="content">发送到服务器的 HTTP 请求内容。</param> /// <param name="headers">请求的头部信息</param> /// <param name="authentication">请求的验证信息</param> /// <returns></returns> public static async Task <T> PostAsync <T>(string uri, string content, IDictionary <string, string> headers = null, AuthenticationHeaderValue authentication = null) { HttpClient c = null; HttpContent httpContent = null; HttpResponseMessage msg = null; T TEntity = default(T); try { c = new HttpClient(); httpContent = new StringContent(content); if (headers != null) { foreach (var kv in headers) { c.DefaultRequestHeaders.Add(kv.Key, kv.Value); } } if (authentication != null) { c.DefaultRequestHeaders.Authorization = authentication; } msg = await c.PostAsync(uri, httpContent); string json = await msg.Content.ReadAsStringAsync(); // ReadAsAsync TEntity = SerializeHelper.DeserializeFromJson <T>(json); } catch (WebException we) { WebHelper.ThrowWebException(we); throw; } finally { if (httpContent != null) { httpContent.Dispose(); } if (c != null) { c.Dispose(); } if (msg != null) { msg.Dispose(); } } return(TEntity); }
/// <summary> /// HttpWebRequest 用GET方法访问指定URI<c>使用完记得调用Stream.Close方法</c> /// </summary> /// <param name="uri">请求发送到的 URI。</param> /// <param name="headers">请求的头部信息</param> /// <param name="contentType">请求的验证信息</param> /// <param name="proxy">代理</param> /// <returns></returns> public static Stream HttpGet(string uri, IDictionary <string, string> headers = null, string contentType = "text/json", WebProxy proxy = null) { #if netcore if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } #endif #if net45 if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } #endif #if net40 if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072; } #endif HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; request.Method = "GET"; request.ContentType = contentType; if (headers != null) { foreach (var kv in headers) { request.Headers.Add(kv.Key, kv.Value); } } if (proxy != null) { request.Proxy = proxy; } try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; return(response.GetResponseStream()); } catch (WebException we) { WebHelper.ThrowWebException(we); throw; } }
/// <summary> /// HttpClient 用POST方法访问指定URI /// </summary> /// <param name="uri">请求发送到的 URI。</param> /// <param name="content">发送到服务器的 HTTP 请求内容。</param> /// <param name="token">请求的验证信息</param> /// <param name="headers">请求的头部信息</param> /// <returns></returns> public static async Task <HttpContent> PostAsync(string uri, string content, string token, IDictionary <string, string> headers) { HttpClient c = null; HttpContent httpContent = null; HttpResponseMessage msg = null; try { c = new HttpClient(); httpContent = new StringContent(content, Encoding.UTF8, "application/json"); //httpContent.Headers.Add("Content-Type", "application/json"); if (headers != null) { foreach (var kv in headers) { c.DefaultRequestHeaders.Add(kv.Key, kv.Value); } } if (!string.IsNullOrEmpty(token)) { c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token); } msg = await c.PostAsync(uri, httpContent); return(msg.Content); } catch (WebException we) { WebHelper.ThrowWebException(we); throw; } finally { if (httpContent != null) { httpContent.Dispose(); } if (c != null) { c.Dispose(); } } }
/// <summary> /// HttpClient 用GET方法访问指定URI <c>用完注意调用HttpContent.Dispose方法</c> /// </summary> /// <param name="uri">请求发送到的 URI。</param> /// <param name="token">Basic 验证模式的令牌</param> /// <param name="headers">请求的头部信息</param> /// <returns></returns> public static async Task <HttpContent> GetAsync(string uri, string token, IDictionary <string, string> headers = null) { HttpClient c = null; try { c = new HttpClient(); if (headers != null) { foreach (var kv in headers) { c.DefaultRequestHeaders.Add(kv.Key, kv.Value); } } if (!string.IsNullOrEmpty(token)) { c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token); } var r = await c.GetAsync(uri); return(r.Content); } catch (WebException we) { WebHelper.ThrowWebException(we); throw; } finally { if (c != null) { c.Dispose(); } } }
// 发起 HTTP请求 static async Task <HttpResponseMessage> SendAsync(string uri, HttpConfiguration configuration, int tryTimes, int sleep) { if (uri != null) { #if netcore if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } #endif #if net45 if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } #endif #if net40 if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072; } #endif } // 初始化 HTTP 消息处理程序 HttpClientHandler handler = null; if (configuration != null) { if (configuration.Proxy != null) { handler = new HttpClientHandler { Proxy = configuration.Proxy, UseProxy = true } } ; if (configuration.CookieContainer != null) { if (handler != null) { handler.CookieContainer = configuration.CookieContainer; } else { handler = new HttpClientHandler { CookieContainer = configuration.CookieContainer } }; } } var client = handler != null ? new HttpClient(handler) : new HttpClient(); if (configuration != null && configuration.Timeout != null) { client.Timeout = new TimeSpan(0, 0, 0, 0, configuration.Timeout.Value); } // 初始化 HTTP 请求 var method = System.Net.Http.HttpMethod.Get; if (configuration != null) { if (configuration.Method == HttpMethod.Get) { method = System.Net.Http.HttpMethod.Get; } else if (configuration.Method == HttpMethod.Post) { method = System.Net.Http.HttpMethod.Post; } else if (configuration.Method == HttpMethod.Put) { method = System.Net.Http.HttpMethod.Put; } else if (configuration.Method == HttpMethod.Delete) { method = System.Net.Http.HttpMethod.Delete; } else if (configuration.Method == HttpMethod.Head) { method = System.Net.Http.HttpMethod.Head; } else if (configuration.Method == HttpMethod.Trace) { method = System.Net.Http.HttpMethod.Trace; } else if (configuration.Method == HttpMethod.Options) { method = System.Net.Http.HttpMethod.Options; } } var request = new HttpRequestMessage(method, uri); if (configuration != null) { if (configuration.Accept != null) { request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(configuration.Accept)); } if (configuration.UserAgent != null) { request.Headers.UserAgent.Add(new ProductInfoHeaderValue(configuration.UserAgent, null)); } if (configuration.KeepAlive != null) { request.Headers.Connection.Add("keep-alive"); } string content = null; if (configuration.Content != null && configuration.Content is string) { content = (string)configuration.Content; } else if (configuration.Content != null) { content = SerializeHelper.SerializeToJson(configuration.Content); } if (content != null) { var encoding = configuration.Encoding ?? Encoding.UTF8; var contentType = configuration.ContentType ?? "application/json"; var httpContent = new StringContent(content, encoding ?? Encoding.UTF8, contentType); request.Content = httpContent; } if (configuration.Headers != null) { // Authorization TODO string scheme = null; string token = null; foreach (var kv in configuration.Headers) { if (string.Equals(kv.Key, "scheme", StringComparison.CurrentCultureIgnoreCase)) { scheme = kv.Key; } else if (string.Equals(kv.Key, "token", StringComparison.CurrentCultureIgnoreCase)) { token = kv.Key; } else { request.Headers.Add(kv.Key, kv.Value); } } if (token != null) { if (scheme == null) { scheme = "Basic"; } request.Headers.Authorization = new AuthenticationHeaderValue("Basic", token); } } } try { var response = await client.SendAsync(request); return(response); } catch (WebException we) { if (handler != null) { handler.Dispose(); } if (client != null) { client.Dispose(); } tryTimes--; if (tryTimes > 0) { System.Threading.Thread.Sleep(sleep); return(await WebHelper.SendAsync(uri, configuration, tryTimes, sleep)); } else { WebHelper.ThrowWebException(we); throw; } } //MultipartFormDataContent => multipart/form-data //FormUrlEncodedContent => application/x-www-form-urlencoded //StringContent => application/json //StreamContent => binary }
// 发起 HTTP请求 static HttpWebResponse Send(string uri, HttpConfiguration configuration, int tryTimes, int sleep) { if (uri != null) { #if netcore if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } #endif #if net45 if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } #endif #if net40 if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072; } #endif } try { // 创建请求 var request = WebRequest.Create(uri) as HttpWebRequest; request.Method = "GET"; // 默认连接最大数=2,如果没有全局设置,则需要设置并发连接数 if (ServicePointManager.DefaultConnectionLimit == 2) { request.ServicePoint.ConnectionLimit = 65532; } if (configuration != null) { request.ContentLength = 0; request.Method = configuration.Method.ToString().ToUpper(); if (configuration.Timeout != null) { request.Timeout = configuration.Timeout.Value; } if (configuration.ContentType != null) { request.ContentType = configuration.ContentType; } if (configuration.Accept != null) { request.Accept = configuration.Accept; } if (configuration.UserAgent != null) { request.UserAgent = configuration.UserAgent; } if (configuration.KeepAlive != null) { request.KeepAlive = configuration.KeepAlive.Value; } if (configuration.Proxy != null) { request.Proxy = configuration.Proxy; } if (configuration.Headers != null) { foreach (var kv in configuration.Headers) { request.Headers.Add(kv.Key, kv.Value); } } if (configuration.CookieContainer != null) { request.CookieContainer = configuration.CookieContainer; } // 写入参数 string content = null; if (configuration.Content != null && configuration.Content is string) { content = (string)configuration.Content; } else if (configuration.Content != null) { content = SerializeHelper.SerializeToJson(configuration.Content); } if (!string.IsNullOrEmpty(content)) { var encoding = configuration.Encoding ?? Encoding.UTF8; byte[] bytes = encoding.GetBytes(content); request.ContentLength = bytes.Length; using (var stream = request.GetRequestStream()) { stream.Write(bytes, 0, bytes.Length); stream.Close(); } } } var response = request.GetResponse() as HttpWebResponse; return(response); } catch (WebException we) { tryTimes--; if (tryTimes > 0) { System.Threading.Thread.Sleep(sleep); return(WebHelper.Send(uri, configuration, tryTimes, sleep)); } else { WebHelper.ThrowWebException(we); throw; } } }
/// <summary> /// HttpWebRequest 用GET方法访问指定URI /// </summary> /// <typeparam name="T"></typeparam> /// <param name="uri">请求发送到的 URI。</param> /// <param name="headers">请求的头部信息</param> /// <returns></returns> public static T HttpGet <T>(string uri, IDictionary <string, string> headers = null) { #if netcore if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } #endif #if net45 if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } #endif #if net40 if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072; } #endif HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; request.Method = "GET"; request.ContentType = "text/json"; if (headers != null) { foreach (var kv in headers) { request.Headers.Add(kv.Key, kv.Value); } } StreamReader reader = null; Stream stream = null; try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; stream = response.GetResponseStream(); reader = new StreamReader(stream); string line = reader.ReadToEnd(); T value = SerializeHelper.DeserializeFromJson <T>(line); return(value); } catch (WebException we) { WebHelper.ThrowWebException(we); throw; } finally { if (stream != null) { stream.Close(); } if (reader != null) { reader.Close(); } } }
/// <summary> /// HttpWebRequest 用POST方法访问指定URI /// </summary> public static T HttpPost <T>(string uri, string content, IDictionary <string, string> headers = null, string contentType = "application/json", int?timeout = null) { //application/x-www-form-urlencoded #if netcore if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } #endif #if net45 if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } #endif #if net40 if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072; } #endif HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; if (timeout != null) { request.Timeout = timeout.Value; } request.Method = "POST"; request.ContentType = contentType; request.ContentLength = 0; if (headers != null) { foreach (var kv in headers) { request.Headers.Add(kv.Key, kv.Value); } } if (!string.IsNullOrEmpty(content)) { byte[] sndBytes = Encoding.UTF8.GetBytes(content); request.ContentLength = sndBytes.Length; Stream rs = request.GetRequestStream(); rs.Write(sndBytes, 0, sndBytes.Length); rs.Close(); } StreamReader reader = null; Stream stream = null; try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; stream = response.GetResponseStream(); reader = new StreamReader(stream); string line = reader.ReadToEnd(); T value = SerializeHelper.DeserializeFromJson <T>(line); return(value); } catch (WebException we) { WebHelper.ThrowWebException(we); throw; } finally { if (stream != null) { stream.Close(); } if (reader != null) { reader.Close(); } } }
/// <summary> /// HttpWebRequest 用POST方法访问指定URI<c>使用完记得调用Stream.Close方法</c> /// </summary> public static HttpWebResponse HttpResponse(string uri, string content, IDictionary <string, string> headers = null, string contentType = "application/json", int?timeout = null, Encoding encoding = null) { //application/x-www-form-urlencoded encoding = encoding ?? Encoding.UTF8; #if netcore if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } #endif #if net45 if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } #endif #if net40 if (uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072; } #endif HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; if (timeout != null) { request.Timeout = timeout.Value; } request.Method = "POST"; request.ContentType = contentType; request.ContentLength = 0; if (headers != null) { foreach (var kv in headers) { request.Headers.Add(kv.Key, kv.Value); } } if (!string.IsNullOrEmpty(content)) { byte[] sndBytes = encoding.GetBytes(content); request.ContentLength = sndBytes.Length; Stream rs = request.GetRequestStream(); rs.Write(sndBytes, 0, sndBytes.Length); rs.Close(); } try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; return(response); } catch (WebException we) { WebHelper.ThrowWebException(we); throw; } }