关于HttpWebRequest模拟Web登陆和更新的WinForm程序问题,郁闷好几天了!请求大家帮忙.
最近在做一个WinForm程序,主要功能是实现自动登陆并且重定向到一个更新页面实现数据更新的操作.我写了一个函数,验证登陆是成功的,但是更新就不行了.代码如下:
public ErrorCode InsertSnippet(SiteID TheSiteID, string SiteLoginURL,string SiteInsertURL, string Username, string Password, int Timeout, int NumOfTries, string Snippet, ref string sMessage)
{
//Check the login
string str_path = SiteLoginURL;
string cookieheader = null;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(str_path);
HttpWebResponse response = null;
Stream dataStream = null;
request.Method = "POST"; //Set the Method property of the request to POST
request.ContentType = "application/x-www-form-urlencoded"; //Set the ContentType property of the webrequest
request.AllowAutoRedirect = true;
CookieContainer cookCT = new CookieContainer();
request.CookieContainer = cookCT;
string postdata = ""; //Create POST data and convert it to a byte array
postdata = "email=" + Username + "&password=" + Password + "&type=1"; //post data of the hi5.com site
byte[] byteArray = Encoding.UTF8.GetBytes(postdata);
request.ContentLength = byteArray.Length; //Set the ContentLength property of the WebRequest
request.Timeout = Timeout;
try
{
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = (HttpWebResponse)request.GetResponse();//Gets the response information
cookieheader = request.CookieContainer.GetCookieHeader(new Uri(SiteLoginURL));
sMessage = response.StatusDescription;
}
catch (Exception e)
{
sMessage = e.Message.ToString();
throw (new Exception(e.Message.ToString(), e));
}
string PostData = null;
str_path = SiteInsertURL;
request = null;
request = (HttpWebRequest)HttpWebRequest.Create(SiteInsertURL);
response = null;
dataStream = null;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
CookieContainer newcc = new CookieContainer();
request.CookieContainer = newcc;
request.CookieContainer.SetCookies(new Uri(SiteInsertURL), cookieheader);
request.AllowAutoRedirect = true;
PostData = "timestamp=1161741302148&orientationStatus=&origOrientationStatus=&drinkerStatus=&origDrinkerStatus=&smokerStatus=&origSmokerStatus=&description="+Snippet.ToString()+"&matchDescription="; //post data to hi5.com site
byte[] ByteArray = Encoding.UTF8.GetBytes(PostData);
request.ContentLength = ByteArray.Length;
request.Timeout = Timeout;
try
{
dataStream = request.GetRequestStream();
dataStream.Write(ByteArray, 0, ByteArray.Length);
dataStream.Close();
response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader sreader = new StreamReader(dataStream, ASCIIEncoding.UTF8);
string str = sreader.ReadToEnd();
sMessage = response.ResponseUri.AbsoluteUri;
}
catch (Exception e)
{
sMessage = e.Message.ToString();
throw (new Exception(e.Message.ToString(), e));
}
finally
{
dataStream.Close();
response.Close();
}
return ErrorCode.Success;
}