模拟Post/get提交数据 并抓取返回数据

来源:互联网 发布:英文软件汉化 编辑:程序博客网 时间:2024/05/16 11:40

最近需要做的项目中,使用httpwebrequest httpwebrespone来模拟提交数据

还有模拟用户登录后提交数据。

下面做个简单一点的。模拟post提交数据,get在前面的抓取sina的天气预报也使用到了。

下面是代码




//提交的post数据

            string postData = string.Format("account={0}&reaccount={0}&cardcode={1}&cardpassword={2}",txtLoginId.Text,txtCardNo.Text,txtPass.Text);
            postData += string.Format("&__EVENTTARGET={0}&__EVENTARGUMENT=&__VIEWSTATE={1}", "nextStep", "YToxOntzOjExOiJjdXJyZW50VXNlciI7YjowO30=");
            HttpWebResponse response;
            HttpWebRequest request;
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(postData);
            request = (HttpWebRequest)WebRequest.Create("url");
            data = encoding.GetBytes(postData);
            request.Method = "POST";
            request.ProtocolVersion = HttpVersion.Version10;
            request.UserAgent = "Mozilla/4.0";


            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(data, 0, data.Length);
            stream.Close();
            string html = string.Empty;
            try
            {
                //获取服务器返回的资源
                response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                html = reader.ReadToEnd();
                reader.Close();
                response.Close();
                textBox1.Text = html;
            }
            catch (Exception ex)
            {
                label4.Text = ex.Message;
            }
原创粉丝点击