HttpWebRequest和HttpWebResponse的应用
创建使用类HttpHelper:
public class Httpparam { public string UserAgent { get; set; } public string Accept { get; set; } public string ContentType { get; set; } public string Referer { get; set; } } public class HttpHelper { //下载源码 public static string GetString(string url, Httpparam para, Encoding encoding) { var res = (HttpWebRequest)HttpWebRequest.Create(new Uri(url)); res.ContentType = para.ContentType; res.Accept = para.Accept; res.UserAgent = para.UserAgent; res.Referer = para.Referer; var stream = new StreamReader(res.GetResponse().GetResponseStream(), encoding); var result=stream.ReadToEnd(); stream.Close(); stream.Dispose(); res.Abort(); return result; } //上传数据 public static string PostData(string url, Httpparam para, Encoding encoding,string data) { var buf = encoding.GetBytes(data); var res = (HttpWebRequest)HttpWebRequest.Create(new Uri(url)); res.Method = "post"; res.ContentType = para.ContentType; res.Accept = para.Accept; res.UserAgent = para.UserAgent; res.Referer = para.Referer; var reqstream = res.GetRequestStream(); reqstream.Write(buf, 0, buf.Length); reqstream.Close(); reqstream.Dispose(); var stream = new StreamReader(res.GetResponse().GetResponseStream(), encoding); var result = stream.ReadToEnd(); stream.Close(); stream.Dispose(); res.Abort(); return result; } }