1. 程式人生 > >HttpWebRequest和HttpWebResponse的應用

HttpWebRequest和HttpWebResponse的應用

post accep quest reader esp str adt data turn

創建使用類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; } }

HttpWebRequest和HttpWebResponse的應用