日期:2014-05-17 浏览次数:20907 次
public class HttpHelper { public static string contentType = "application/x-www-form-urlencoded"; public static string accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*"; public static string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; Zune 4.7; BOIE9;ZHCN)"; public static string referer = ""; /// <summary> /// 获取HTML /// </summary> /// <param name="url"></param> /// <param name="cookieContainer"></param> /// <param name="method">GET or POST</param> /// <param name="postData">like "username=admin&password=123"</param> /// <returns></returns> public static string GetHtml(string url, CookieContainer cookieContainer = null, string method = "GET", string postData = "") { cookieContainer = cookieContainer ?? new CookieContainer(); HttpWebRequest httpWebRequest = null; HttpWebResponse httpWebResponse = null; try { httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); httpWebRequest.CookieContainer = cookieContainer; httpWebRequest.ContentType = contentType; httpWebRequest.Referer = referer; httpWebRequest.Accept = accept; httpWebRequest.UserAgent = userAgent; httpWebRequest.Method = method; httpWebRequest.ServicePoint.ConnectionLimit = int.MaxValue; if (method.ToUpper() == "POST") { byte[] byteRequest = Encoding.Default.GetBytes(postData); Stream stream = httpWebRequest.GetRequestStream(); stream.Write(byteRequest, 0, byteRequest.Length); stream.Close(); } httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); Stream responseStream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8); string html = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); httpWebRequest.Abort(); httpWebResponse.Close(); return html; } catch (Exception) { return string.Empty; } } }