Link to home
Start Free TrialLog in
Avatar of futurebuilders

asked on

Send Login details through HTTPRequest Object


I have to send Login details using HTTPRequest class and get the validated result.

Please let me know the code examples.

Avatar of kris_per

If the login is for form based server authentication (like the ones where you log in a web page), then you have to POST the username and password details using HttpWebRequest as shown in the sample code below:
string postDataString = "";
            postDataString += "username" + "=" + UserName;
            postDataString += "&password" + "=" + Password; // here the &username and &password 
// tags should be the same as used in web page form which can be seen using View Source for the 
//html page

            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
            byte[] postDataBytes = asciiEncoding.GetBytes(postDataString);

            Uri uriLoginForm = new Uri(" page address here");

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uriLoginForm);
            webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            webRequest.Referer = ""; // actual website address here
            webRequest.KeepAlive = true;
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = postDataBytes.Length;            
            webRequest.AllowAutoRedirect = false;
            webRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

            System.IO.Stream outStream = webRequest.GetRequestStream();
            outStream.Write(postDataBytes, 0, postDataBytes.Length);

            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            StreamReader streamReader = new System.IO.StreamReader(webResponse.GetResponseStream());
            string respString = streamReader.ReadToEnd();


Open in new window

Avatar of futurebuilders


hi kris,

Thanks for your reply.Will this code be used to validate the userid and password. If yes then how should i read that validation code from werresponse?

In response string I am getting complete HTML code. How to determine whether my user name and password are valid or invalid. Please let me know

If authentication has failed, then the html code you recieved will have the error message like 'login failed' somewhere in that html response...this html code is the same page as it would appear in the browser when you enter wrong username/ find where the error message is in the html codeL: write the response string to a text file named for e.g. login_response.htm...and then open this htm file in a browser and then in notepad to identify the location of where the error message is in the html...then accordingly you can code in c# to check for that message...(alternatively instead of saving the response to txt file in code, you can set breakpoint just after getting response, then can move the mouse over the response-text variable name which will show the value like toolip and you can copy the value from there and paste into a txt file and then save)

If authentication is successful, then you would get the same html code as it would come in the browser after logging in successfully....this would be typically a default web page for the user (like say after successfull login in gmail, it goes to inbox)

Thnks for your support.

I did the same as you said. But I did nt get any login related information.Can u please check the response code and let me know whether I am in right way or not.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "">
<html xmlns="">
<title>World of Warcraft Account Login</title>
<meta http-equiv="imagetoolbar" content="false"/>
<link rel="shortcut icon" href="/login/static/_themes/wam/img/favicon.ico" type="image/x-icon"/>
<link rel="stylesheet" type="text/css" href="/login/static/_themes/wam/css/master.css?v1"/>
<!--[if IE 6]><link rel="stylesheet" type="text/css" href="/login/static/_themes/wam/css/master-ie6.css?v1" /><![endif]-->
<link rel="stylesheet" type="text/css" href="/login/static/_themes/wam/css/_lang/en-us.css?v1"/>
<script type="text/javascript" src="/login/static/_themes/common.js?v1"></script>
<script type="text/javascript" src="/login/static/_themes/jquery.js?v1"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
var processingStr = "Processing";
<body class="en-us">
<div class="page loginView">
<div class="">
<form id="loginForm" class="submitForm" name="loginForm" method="post"
action="?app=wam&amp;" onsubmit="login.disableButton('submit', this); return true;">
<div class="formRow accountName">
<label class="formLabel" for="accountName" style="margin-bottom:1px"> E-mail Address</label>
<input value="" id="accountName"
name="accountName" maxlength="320" type="text" tabindex="1" class="text" />
<div class="errorTooltip">
<div class="tooltipBg">
Account name required.<br />
<div class="arrow"></div>
<script type="text/javascript">
<div class="formRow password">
<label class="formLabel" for="password">Password</label>
<input id="password" name="password"
maxlength="16" type="password" tabindex="2" autocomplete="off" class="text" />
<input type="submit" class="hiddenSubmit" />
<a class="submit" href="javascript:;" onclick="Form.submit(this)" tabindex="3">Log In</a>
<div class="signUp">
<p>Forgot your account <a href="">password</a>?
<p>Don't have an account yet? <a href="">Sign up now</a>!</p>
<input type="hidden" name="persistLogin" id="persistLogin" value="on" />
<div class="selectLocale">
<p>To view this page in another language:</p>
<a href="javascript:selectLanguage('de-de');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'de_DE')">Deutsch</a>
<a href="javascript:selectLanguage('en-us');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'en_US')">English (US)</a>
<a href="javascript:selectLanguage('en-gb');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'en_GB')">English (EU)</a>
<a href="javascript:selectLanguage('es-mx');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'es_MX')">Español (AL)</a>
<a href="javascript:selectLanguage('es-es');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'es_ES')">Español (EU)</a>
<a href="javascript:selectLanguage('fr-fr');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'fr_FR')">Français</a>
<a href="javascript:selectLanguage('ru-ru');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'ru_RU')">¿¿¿¿¿¿¿</a>
<a href="javascript:selectLanguage('ko-kr');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'ko_KR')">¿¿¿</a>
<div class="legal">
<p>For security reasons, close your web browser when you are done accessing services that require authentication! Secure Blizzard Entertainment web pages that request your account name and password will contain URLs such as,, and</p>
<div class="legalLinks">
<a href=""
onclick=";return false;">Online Privacy Policy</a> |
<a href=""
onclick=";return false;">Blizzard Terms of Use</a> |
<a href="">Customer Support</a><br />
<a href=""
onclick=";return false;">&copy;2010 Blizzard Entertainment, Inc. All rights reserved.</a>
<a class="esrb" href=""><!-- --></a>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker('UA-544112-16');
function _gaInit() {
function _htmlDomInit(doc) {
_htmlDom = doc;
/* Partial workaround for Firefox bug 230214 */
if(typeof(document.cookie) == 'undefined') {
var obj = document.createElementNS('', 'object');
obj.setAttribute('style', 'display:none');
obj.width = 0;
obj.height = 0;
obj.type = 'text/html'; = 'data:text/html;charset=utf-8,%3Cscript%3Eparent._htmlDomInit%28document%29%3C/script%3E';
document.__defineGetter__('cookie', function() { return _htmlDom.cookie; });
document.__defineSetter__('cookie', function(c) { _htmlDom.cookie = c; });
} else
} catch(err) {}
Avatar of kris_per

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

I migrated your code in to class file as I am using for development.

1st I called Login method.If I give username and password correct then this method is returning nothing.If I give username or password this method returning the html page content.

So what does it mean? If credentails are correct then It will return nothing ??

Please provide the answer for my question.


I think there mustbe some html content after successful login. It will be the content of the page you would get in browser if you login in the browser (for example in gmail, after login next page is inbox or some default page).

If you login to worldofwarcraft in browser what is the page you get? Is it a standard html page?

OK. I have just tested this with my worldofwarcraft account and I too have got the same empty result...The fix for this is:

Set AllowAutoRedirect to true in the Login method in the above code.

webRequest.AllowAutoRedirect = true;

After this I have got a valid html content which has my Account Summary with all the 'change email address' links etc...

So make this correction and i hope you too would get the result....
Thanks...I will try the above code.

Login method will validates the credentials and if the credentials are valid then it will return login page code.

What is the purpose of method "GetWebPageContent"? And where we will use it? Do we need to call after login method? And what purpose we will use thia method?

Please let me know.

GetWebPageContent is to get any page other than the one returned by login...i.e. After successful login, a default page (e.g. account summary) is returned. If you want to get page other than this, then GetWebPageContent can be used after login.

So in this case 1st I should use login method to validate the login credentials
next I want to go to password change page.To do that i have to call method GetWebPageContent .Right?


With your help now i am able to validate the credentials and able to change the password.

Now my requiing rement is after validating the credentials i have to open the inner home page of the web site and show to user.

How can DO that.What nethod i have to use?

Using the GetWebPageContent method, you can get the html data for the inner home page from the website, save it to a local temp file with .htm extension and then open this temp.htm file in web browser using Process.Start() method as shown below:

ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
startInfo.Arguments = @"C:\temp\temp.htm";

But note that since authentication has done in the .net program, same authenticated state will not be carried to the browser. User can just view the page.

But my requirement is user should be able to carry the authentication details and he can navigate in to the site.

The base idea here is we are storing user credentials in local data base and when ever user enters user id, we are retrieving his password from local DB and using these credentials to login in to the system- so that user no need to remember his password al times.

PLease provide some solution

Thing is authentication is done in .net code and you want to use the same authentication state in the browser after that.  I am not sure if thats possible as the .net code and browser are different apps. I think this needs more understanding on how the authentication state is stored internally (like cookies or anything more). I will see if I can do some experiments on this and find something; but I am not sure. Better you look for chances with other experts also by posting another question to see if any other expert has already have the knowledge on this.

I got some reference site in other post.With this i am able to open the url in windows application.

But still i did not understand how to pass values to it.

I think if u see them u will get some idea

PLease see above sites and let me know if you get any idea

Thanks in advance

OK. Using WebBrowser control is one option that came to my mind. But still i am not positive about that as well. I would suggess you try the following tests. But note that with WebBrowser control user is tied up using only the windows forms and cant use separate browser.

Test #1:

Create a  Form
Add a button named Login at the top
Add another button named 'Goto page'
Add a WebBrowser control below the buttons

In the login button click, Do the login using the code in the solution above.
In the 'goto page' button, open the inner page (for example change password url) in the webbrowser control (using I think Navigate method of webbrowser control)

Now user clicks Login button. login is done.
Then user clicks the goto page button. this will open the page in the wbebrowser; see if authentication is maintained there or not.

Test 2:
Create a form
Add a button 'Goto login page'
Add another button 'Fill username/pwd'
Add webbrowser control below

When user clicks goto login page, open the login page in webbrowser
Then user will click 'Fill username/pwd' button. This will get the username/pwd from another store and should fill the username and pwd in the opened web page. I dont have a tested code for this now. One option is to use WebBrowser.Document property to find out the username/pwd textboxes and set the values in it. I will see if I can try this and find.
Then user will click the login button in the web page and continue browsing inside the webbrowser.

As I mentioned above, user is tied up with using your win forms app for this.

Option 3:

Is requirement like 'autofill and remember password' feature of the browser? Then why can't you try for an option like that within the context of the browser, like IE Extension plugin, like what Google toolbar does OR using Activex control...? I dont know how exactly to make these things work for your requirement...but I am just throwin some thoughts that might click something for you.