1 /// <summary> 2 /// 有关HTTP请求的辅助类 3 /// </summary> 4 public class HttpQuery 5 { 6 PRivate static readonly string DefaultUserAgent = 7 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 8 9 public static void Get(string url, object data, Action<string> callback) 10 { 11 IDictionary<string, string> parameters = Getparameters(data); 12 13 if (!(parameters == null || parameters.Count == 0)) 14 { 15 url += "?"; 16 foreach (var item in parameters) 17 { 18 url += item.Key + "=" + item.Value + "&"; 19 } 20 } 21 CreateGetHttpResponse(url, null, null, null, callback); 22 } 23 24 public static void Post(string url, object data, Action<string> callback) 25 { 26 IDictionary<string, string> parameters = Getparameters(data); 27 28 CreatePostHttpResponse(url, parameters, null, null, Encoding.UTF8, null, callback); 29 } 30 31 public static void Post(string url, string data, Action<string> callback) 32 { 33 CreatePostHttpResponse(url, data, null, null, Encoding.UTF8, null, callback); 34 } 35 36 private static IDictionary<string, string> Getparameters(object data) 37 { 38 if (data == null) 39 { 40 return new Dictionary<string, string>(); 41 } 42 IDictionary<string, string> parameters = new Dictionary<string, string>(); 43 44 Type type = data.GetType(); 45 PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); 46 foreach (PropertyInfo p in props) 47 { 48 parameters.Add(p.Name, p.GetValue(data).ToString()); 49 } 50 51 return parameters; 52 } 53 54 /// <summary> 55 /// 创建GET方式的HTTP请求 56 /// </summary> 57 /// <param name="url">请求的URL</param> 58 /// <param name="timeout">请求的超时时间</param> 59 /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param> 60 /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param> 61 /// <returns></returns> 62 private static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, 63 CookieCollection cookies, Action<string> callback, string encoding = "utf-8") 64 { 65 if (string.IsNullOrEmpty(url)) 66 { 67 return null; 68 //throw new ArgumentNullException("url"); 69 } 70 try 71 { 72 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 73 request.Method = "GET"; 74 request.UserAgent = DefaultUserAgent; 75 if (!string.IsNullOrEmpty(userAgent)) 76 { 77 request.UserAgent = userAgent; 78 } 79 if (timeout.HasValue) 80 { 81 request.Timeout = timeout.Value; 82 } 83 if (cookies != null) 84 { 85 request.CookieContainer = new CookieContainer(); 86 request.CookieContainer.Add(cookies); 87 } 88 89 HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse; 90 91 StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(), 92 System.Text.Encoding.GetEncoding(encoding)); 93 94 string html = ""; 95 //获取请求到的数据 96 html = reader.ReadToEnd(); 97 //关闭 98 httpWebResponse.Close(); 99 reader.Close();100 101 Regex regex = new Regex("charset=(?<code>//w+)/"");102 Match match = regex.Match(html);103 string code = match.Groups["code"].Value;104 if (!string.IsNullOrWhiteSpace(code) && code.ToLower() != encoding.ToLower())105 {106 return CreateGetHttpResponse(url, timeout, userAgent, cookies, callback, code);107 }108 else109 {110 callback(html);111 return httpWebResponse;112 }113 }114 catch115 {116 callback(null);117 }118 return null;119 }120 121 /// <summary> 122 /// 创建POST方式的HTTP请求 123 /// </summary> 124 /// <param name="url">请求的URL</param> 125 /// <param name="parameters">随同请求POST的参数名称及参数值字典</param> 126 /// <param name="timeout">请求的超时时间</param> 127 /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param> 128 /// <param name="requestEncoding">发送HTTP请求时所用的编码</param> 129 /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param> 130 /// <returns></returns> 131 private static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters,132 int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies, Action<string> callback)133 {134 if (string.IsNullOrEmpty(url))135 {136 throw new ArgumentNullException("url");137 }138 if (requestEncoding == null)139 {140 throw new ArgumentNullException("requestEncoding");141 }142 HttpWebRequest request = null;143 try144 {145 //如果是发送HTTPS请求 146 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))147 {148 ServicePointManager.ServerCertificateValidationCallback =149 new RemoteCertificateValidationCallback(CheckValidationResult);150 request = WebRequest.Create(url) as HttpWebRequest;151 request.ProtocolVersion = HttpVersion.Version10;152 }153 else154 {155 request = WebRequest.Create(url) as HttpWebRequest;156 }157 request.Method = "POST";158 request.ContentType = "application/x-www-form-urlencoded";159 160 if (!string.IsNullOrEmpty(userAgent))161 {162 request.UserAgent = userAgent;163 }164 else165 {166 request.UserAgent = DefaultUserAgent;167 }168 169 if (timeout.HasValue)170 {171 request.Timeout = timeout.Value;172 }173 if (cookies != null)174 {175 request.CookieContainer = new CookieContainer();176 request.CookieContainer.Add(cookies);177 }178 //如果需要POST数据 179 if (!(parameters == null || parameters.Count == 0))180 {181 StringBuilder buffer = new StringBuilder();182 int i = 0;183
新闻热点
疑难解答