using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Net.Security; using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; namespace Admin.Core.Socket.Helper { public class HttpRequestUtility { /// /// The default user agent /// private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; private static CookieCollection cookieCollection = new CookieCollection(); #region Post方式请求URL,并返回T类型 /// /// Post方式请求URL,并返回T类型 /// /// 接收JSON的数据类型 /// 传入的url /// 传入的对象 public static T PostJson(string url, string data, string token, string flag) { // JavaScriptSerializer js = new JavaScriptSerializer(); string returnText = Post(url, data, token, flag);//使用get获取 //T result = js.Deserialize(returnText); T result = JsonConvert.DeserializeObject(returnText); return result; } #endregion #region Post发送请求 /// /// Post发送请求 /// /// 请求的url /// 请求的数据 /// 安全token /// 标识login:登陆,user,rToken:获取用户、设备数据 /// 返回值 public static string Post(string url, string data, string token, string flag) { string result = string.Empty; try { var response = PostHttpResponse(url, data, token, 50000, DefaultUserAgent, flag, Encoding.UTF8, cookieCollection); var stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); result = reader.ReadToEnd(); stream.Close(); } catch (Exception ex) { throw ex; } return result; } #endregion #region 创建Post方式的HTTP请求 public static HttpWebResponse PostHttpResponse(string url, string content, string token, int? timeout, string userAgent, string flag, Encoding requestEncoding, CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } if (requestEncoding == null) { throw new ArgumentNullException("requestEncoding"); } HttpWebRequest request = null; //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST"; //获取token使用 if (flag == "login") { SetHeaderValue(request.Headers, "X-Requested-With", "XMLHttpRequest"); SetHeaderValue(request.Headers, "Content-type", "application/json"); } if (flag == "user" || flag == "rtoken") { SetHeaderValue(request.Headers, "Authorization", "Bearer " + token);//刷新的token } if (flag == "Authorization") { SetHeaderValue(request.Headers, "Content-type", "application/json"); SetHeaderValue(request.Headers, "Authorization", "Bearer " + token); } if (flag == "userInfo") { SetHeaderValue(request.Headers, "Content-type", "application/json"); SetHeaderValue(request.Headers, "UserName", "admin"); SetHeaderValue(request.Headers, "Password", "ZmVuZ3RhaXpoYW4xMjM="); } if (flag == "zhiwucloud") { SetHeaderValue(request.Headers, "Content-type", "application/x-www-form-urlencoded;charset=UTF-8"); SetHeaderValue(request.Headers, "Authorization", "Basic MGUyZjNjN2RlMjRkNzkxYTA3MDY1NmI2NzhiMTBiMWUwYzg4NDg4MzphZGJlZmYxYjUyNjliMDE1YzBmYzZiNDJlZjhkZjQwN2ZkNjlhNmIw"); } if (flag == "hnt") { SetHeaderValue(request.Headers, "Content-type", "application/json;charset=UTF-8"); } if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } else { request.UserAgent = DefaultUserAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //如果需要POST数据 byte[] data = requestEncoding.GetBytes(content); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } return request.GetResponse() as HttpWebResponse; } #endregion #region 往head头部加信息 // /// 往head头部加信息 /// /// /// /// public static void SetHeaderValue(WebHeaderCollection header, string name, string value) { var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic); if (property != null) { var collection = property.GetValue(header, null) as NameValueCollection; collection[name] = value; } } #endregion #region Checks the validation result. /// /// Checks the validation result. /// /// The sender. /// The certificate. /// The chain. /// The errors. /// true if XXXX, false otherwise. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //总是接受 } #endregion #region Get方式请求URL,并返回T类型 /// /// GET方式请求URL,并返回T类型 /// /// 接收JSON的数据类型 /// 传入的url /// /// 允许最大JSON长度 /// 传入的对象 public static T GetJson(string url, string token, string flag) { // JavaScriptSerializer js = new JavaScriptSerializer(); string returnText = Get(url, token, flag);//使用get获取 // T result = js.Deserialize(returnText); string rt = returnText.Replace("params", "param"); T result = JsonConvert.DeserializeObject(rt); return result; } #endregion #region Get发送请求 /// /// Post发送请求 /// /// 请求的url /// 请求的数据 /// 安全token /// 标识login:登陆,user,rToken:获取用户、设备数据 /// 返回值 public static string Get(string url, string token, string flag) { string result = string.Empty; try { var response = GetHttpResponse(url, token, 50000, DefaultUserAgent, flag, Encoding.UTF8, cookieCollection); using (var stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream); result = reader.ReadToEnd(); stream.Close(); } } catch (Exception ex) { throw ex; } return result; } #endregion #region 创建Get方式的HTTP请求 public static HttpWebResponse GetHttpResponse(string url, string token, int? timeout, string userAgent, string flag, Encoding requestEncoding, CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } if (requestEncoding == null) { throw new ArgumentNullException("requestEncoding"); } HttpWebRequest request = null; //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "GET"; //获取token使用 if (flag == "user" || flag == "rtoken") { SetHeaderValue(request.Headers, "Authorization", "Bearer " + token);//刷新的token } if (flag == "zhiwucloud") { SetHeaderValue(request.Headers, "Content-type", "application/json"); //SetHeaderValue(request.Headers, "Authorization", "Basic MGUyZjNjN2RlMjRkNzkxYTA3MDY1NmI2NzhiMTBiMWUwYzg4NDg4MzphZGJlZmYxYjUyNjliMDE1YzBmYzZiNDJlZjhkZjQwN2ZkNjlhNmIw"); } if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } else { request.UserAgent = DefaultUserAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } return request.GetResponse() as HttpWebResponse; } #endregion } }