关于C#提交表单post和get的实现 HttpWebRequest 和ttpebeponse
private void post_Click(object sender, EventArgs e) { string html = String.Empty; HttpWebRequest cnbogs = (HttpWebRequest)System.Net.WebRequest.Create("http://music.baidu.com/"); cnbogs.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/QVOD, application/QVOD, */*"; cnbogs.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; MALN; CIBA; InfoPath.2; .NET4.0C; .NET4.0E; Media Center PC 6.0; Tablet PC 2.0; AskTB5.6)"; cnbogs.Method = "Post"; cnbogs.KeepAlive = false; cnbogs.ContentType = "application/x-www-form-urlencoded"; cnbogs.ProtocolVersion = HttpVersion.Version10;//不设置这个可能为出现连接中断 String content = "key=mm";//参数抓个包吧,如果是post方式提交的 参数要按照它的格式; Encoding encod = Encoding.UTF8; byte[] data = encod.GetBytes(content); cnbogs.ContentLength = data.Length; Stream stream = cnbogs.GetRequestStream();//以byte流的方式写入 stream.Write(data, 0, data.Length); stream.Flush(); stream.Close(); HttpWebResponse cnblogsRespone = (HttpWebResponse)cnbogs.GetResponse(); if (cnblogsRespone != null && cnblogsRespone.StatusCode == HttpStatusCode.OK) { using (StreamReader sr = new StreamReader(cnblogsRespone.GetResponseStream())) { html = sr.ReadToEnd(); } } textBox1.Text = html; } -------------------------------------------------------------------------------- private void get_Click(object sender, EventArgs e) { string html = String.Empty; HttpWebRequest cnbogs = (HttpWebRequest)System.Net.WebRequest.Create("http://www.baidu.com/s?wd=mm");//参数在url中 wd 是百度input标签的名字 cnbogs.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/QVOD, application/QVOD, */*"; cnbogs.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; MALN; CIBA; InfoPath.2; .NET4.0C; .NET4.0E; Media Center PC 6.0; Tablet PC 2.0; AskTB5.6)"; cnbogs.Method = "GET";//默认为get方法 不写也行 cnbogs.KeepAlive = false; cnbogs.ContentType = "application/x-www-form-urlencoded"; HttpWebResponse cnblogsRespone = (HttpWebResponse)cnbogs.GetResponse(); if (cnblogsRespone != null && cnblogsRespone.StatusCode == HttpStatusCode.OK) { using (StreamReader sr = new StreamReader(cnblogsRespone.GetResponseStream())) { html = sr.ReadToEnd(); } } textBox1.Text = html; }
最近因为要用到抓取网页的所以研究了下这个。。发现网上好多都不行,总有问题,最后折腾一天还是自己折腾出来的。。发现很奇怪个事。百度无法post。。总会返回错误代码.发现了原来是参数格式不对,我试验了学校的教务网发现post的参数格式,教务是asp.net做的 _viewstate=......&参数, 按照这个格式可以正常提交,所以如果想要以post提交的话抓对应网站的表单包看看格式吧,不行就get提交表单