有很多網站在表單提交時調用腳本,並使用HTTP POST或GET傳遞參數,使用web調試器,我發現參數被傳遞。現在我希望通過C#中的Windows應用程序來做同樣的事情。我怎樣才能實現這樣的功能?在c#中使用windows應用程序執行http方法#
我目前在C#中使用HttpWebRequest和HttpWebResponse類。但是這是一個痛苦,因爲我必須爲每個頁面編寫明確的代碼,我嘗試加載和工作。例如,我試圖將用戶名和密碼傳遞給一個PHP頁面並獲取響應,該響應將發送一個cookie和一個頁面作爲回報,根據該響應來確定用戶是否已登錄。
HttpWebRequest loginreq = createreq("http://www.indyarocks.com/mobile/index.php");
String logintext = "username=" + TxtUsrname.Text + "&pass=" + TxtPasswd.Password + "&button.x=0&button.y=0";
loginreq.ContentLength = logintext.Length;
StreamWriter writerequest = new StreamWriter(loginreq.GetRequestStream());
writerequest.Write(logintext);
writerequest.Close();
HttpWebResponse getloginpageresponse = (HttpWebResponse)loginreq.GetResponse();
cookie = getloginpageresponse.Cookies[0];
BinaryFormatter bf1 = new BinaryFormatter();
Stream f1 = new FileStream("E:\\cookie.dat", FileMode.OpenOrCreate);
bf1.Serialize(f1, cookie);
f1.Close();
string nexturl = getloginpageresponse.Headers[HttpResponseHeader.Location];
StreamReader readresponse = new StreamReader(getloginpageresponse.GetResponseStream());
if (nexturl == "p_mprofile.php")
{
MessageBox.Show("Login Successful");
GrpMsg.IsEnabled = true;
}
else if (nexturl == "index.php?msg=1")
{
MessageBox.Show("Invalid Credentials Login again");
}
這是我createreq類
private HttpWebRequest createreq(string url)
{
HttpWebRequest temp = (HttpWebRequest)WebRequest.Create(url);
temp.Method = "POST";
temp.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; .NET CLR 3.5.21022; FDM)";
temp.KeepAlive = true;
temp.ContentType = "application/x-www-form-urlencoded";
temp.CookieContainer = new CookieContainer();
temp.AllowAutoRedirect = false;
return temp;
}
我在正確的軌道上?有沒有更好的方法來做到這一點?
你有沒有看WebClient類?它包含了很多涉及HttpWebRequest/Response類 – 2009-07-21 18:52:25