问一个关于使用HttpWebRequest发送POST请求的问题
我使用HttpWebRequest发送POST请求去调用一个按钮事件,但由于页面的viewstate老是变来变去,以致服务器端的后台程序总是不会处理,我应该如何办
我把代码贴出来,希望高人帮忙看看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
namespace WinTest
{
public partial class AutoPost : Form
{
public AutoPost()
{
InitializeComponent();
}
private void AutoPost_Load(object sender, EventArgs e)
{
string viewstate = this.getViewState("http://xihuanet.3322.org:8081/GongDanSystem/list_bill1.aspx");
string postString = "__EVENTTARGET=gvBill$ctl07$lbtnZP" + viewstate;
CookieContainer cookieContainer = new CookieContainer();
this.textBox1.Text = this.OpenPageWithPost("http://xihuanet.3322.org:8081/GongDanSystem/list_bill1.aspx", postString, cookieContainer);
}
private string getViewState(string URI)
{
// 设置打开页面的参数
HttpWebRequest request = WebRequest.Create(URI) as HttpWebRequest;
request.Method = "GET";
request.KeepAlive = false;
// 接收返回的页面
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
string srcString = reader.ReadToEnd();
// 获取页面的 VeiwState
string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
int j = srcString.IndexOf("\"", i);
string viewState = srcString.Substring(i, j - i);
// 获取页面的 EventValidation
string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
j = srcString.IndexOf("\"", i);
string eventValidation = srcString.Substring(i, j - i);
viewState = System.Web.HttpUtility.UrlEncode(viewState);
eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);
string formatString = "&__VIEWSTATE={0}&__EVENTVALIDATION={1}";
string postString = string.Format(formatString, viewState, eventValidation);
return postString;
}
private CookieContainer Login(string URI, string postString)
{
// 将提交的字符串数据转换成字节数组
byte[] postData = Encoding.ASCII.GetBytes(postString);
// 设置提交的相关参数
HttpWebRequest request = WebRequest.C