> I am using the HttpWebRequest and HttpWebResponse classes to pull
information from a web server on the internet.
I have an account on one of the webservers that I need to log into
programatically . The connection is not secure (not https, etc.). The
login page just has simple name & password textboxes on it.
Can someone please tell me how I can programatically login using the
HttpWebXXX classes.
This depends on how the login page is designed. If it is a ASP.NET forms
authentication page, you'll have to do a post back.
The easiest approach is to use the System.Net.WebC lient class. As an
example, imagine this is the HTML code for the login page:
<form name="Form1" method="post" action="login.a spx" id="Form1">
<input type="hidden" name="__VIEWSTA TE"
value="dDw1Mzgx O2w8X2N0bDA6X2N 0bDA6X2N0bDA6X2 N0bDc7Pj4" />
<P>Username: <input name="Username" type="text" id="Username" /></P>
<P>Password: <input name="Password" type="text" id="Password" /></P>
<P><input type="submit" name="Login" value="Login" id="Login" /></P>
</form>
The HTTP Request body is made up of ampersand separated key / value pairs.
The request body for the above example will look like this:
Username=Anders &Password=P@ssw ord&Login=Login
This body has to be posted back to the page.
WebClient webClient = new WebClient();
webClient.Heade rs.Add("Content-Type", "applicatio n/x-www-form-urlencoded");
string
requestBody=vie wstate+"Usernam e=Anders&Passwo rd=P@ssword&Log in=Login";
byte[] response = webClient.Uploa dData("http://andersnoras.inf o/login.aspx",
"POST", Encoding.ASCII. GetBytes(reques tBody));
The viewstate variable should include the value of the hidden INPUT field
called __VIEWSTATE. You'll need to extract this value from the initial
request.
If you need to accept cookies from the page, you'll have to use the
HttpWebRequest class:
CookieContainer cookies = new CookieContainer ();
webRequest = WebRequest.Crea te("http://andersnoras.inf o/login.aspx") as
HttpWebRequest;
webRequest.Meth od = "POST";
webRequest.Cont entType = "applicatio n/x-www-form-urlencoded";
webRequest.Cook ieContainer = cookies;
StreamWriter requestWriter = new
StreamWriter(we bRequest.GetReq uestStream());
string
requestBody=vie wstate+"Usernam e=Anders&Passwo rd=P@ssword&Log in=Login";
requestWriter.W rite(requestBod y);
requestWriter.C lose();
webRequest.GetR esponse().Close ();
Anders Norås
http://dotnetjunkies.com/weblog/anoras