如何使用HttpWebResponse自动提交表单

时间:2009-05-25 14:37:43

标签: asp.net screen-scraping httpwebresponse

我正在寻找可以执行以下操作的应用程序

a)使用 HttpWebResponse 以编程方式自动登录到页面(login.asxp),使用已指定的用户名和密码。

b)如果登录成功,则检测重定向URL。

c)提交另一个表单(settings.aspx)以更新数据库中的某些字段。

所需的编码需要使用asp.net

应用程序需要在同一个会话cookie中完成整个过程。

1 个答案:

答案 0 :(得分:0)

string sUrl = "login.aspx";
HttpWebRequest oRequest = (HttpWebRequest)WebRequest.Create(sUrl);
CookieContainer oMyCookies = new CookieContainer();
oRequest.CookieContainer = oMyCookies;
// encode postdata into byte array.  the postdata string format will most likely be different and you'll have to examine the postdata going back and forth using some firefox addon like LiveHTTPHeaders
byte[] oPostData = System.Encoding.UTF8.GetBytes("username=" + HttpUtility.UrlEncode(sUser) + "&pass=" HttpUtility.UrlEncode(sPass));
using (Stream oStream = oRequest.GetRequestStream())
{
    oStream.Write(oPostData, 0, oPostData.Length);
}
HttpWebResponse oResponse = oRequest.GetResponse();
// save response cookies in our cookie object for future sessions!
foreach (Cookie oCookie in oResponse.Cookies)
{
    oMyCookies.SetCookies(sUrl, oCookie.ToString());
}
// maybe check response headers for location
string sResponseContents = null;
using (StreamReader oReader = new StreamReader(oResponse.GetResponseStream())
{
    // store server response into string
    sResponseContents = oReader.ReadToEnd();
}

...这是您想要做的所需的基本代码。