473,729 Members | 2,164 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HttpWebRequests and logging into websites



Hello,

I'm trying to write an app which will periodically log in to a game
website so I can check for changes to some of my player info. The code
I've come up with so far is below, and, as you might have guessed,
doesn't quite work - what I get back is the raw HTML of the login page,
rather than the page I should get after succesfully logging in.

Couple of questions really, am I going in the right direction, and what
do I need to do to make it work?

NB There's also a warning on the login page that if it fails, it is
likely to be with cookies not being enabled, I'm not even really sure
what to do with cookies - this is my first foray into web stuff with C#.

Thanks.

Code:
=====
The form on the login page:

<form method=post action="LoginCh eck">
<input type="text" name="name" size="20" maxlength="20">
<input type="password" name="password" size="20" maxlength="20">
<input type="submit" value="CONTINUE ">
</form>
My code to try to login (m_name, m_password, m_uriLogin all set elsewhere):

ASCIIEncoding encoding = new ASCIIEncoding() ;
string postData = "name=" + m_name + "&password= " + m_password;
byte[] data = encoding.GetByt es(postData);

HttpWebRequest req = (HttpWebRequest )WebRequest.Cre ate(m_uriLogin) ;
req.Method = "POST";
req.ContentType = "applicatio n/x-www-form-urlencoded";
req.ContentLeng th = data.Length;
Stream newStream = req.GetRequestS tream();

newStream.Write (data, 0, data.Length);
newStream.Flush ();
newStream.Close ();

HttpWebResponse resp = (HttpWebRespons e)req.GetRespon se();

Stream istrm = resp.GetRespons eStream();
StreamReader sr = new StreamReader(is trm);
TxtReport.Appen dText(sr.ReadTo End()); // TxtReport is a text box
Jan 10 '06 #1
3 2082
beaker,

The cookie issue is most likely it. HTTP is a stateless protocol. What
you have to do on the HttpWebRequest is to use the CookieContainer property
to set the cookies for the request.

The thing is, once you log in, you will receive cookies back (and there
could possibly be one on your system already from the site, which you might
have to send). You have to take the cookies from the response and feed them
into the next request.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"beaker" <ra************ **@rhubarbblahb lah.net> wrote in message
news:ZM******** ************@fe 3.news.blueyond er.co.uk...


Hello,

I'm trying to write an app which will periodically log in to a game
website so I can check for changes to some of my player info. The code
I've come up with so far is below, and, as you might have guessed, doesn't
quite work - what I get back is the raw HTML of the login page, rather
than the page I should get after succesfully logging in.

Couple of questions really, am I going in the right direction, and what do
I need to do to make it work?

NB There's also a warning on the login page that if it fails, it is likely
to be with cookies not being enabled, I'm not even really sure
what to do with cookies - this is my first foray into web stuff with C#.

Thanks.

Code:
=====
The form on the login page:

<form method=post action="LoginCh eck">
<input type="text" name="name" size="20" maxlength="20">
<input type="password" name="password" size="20" maxlength="20">
<input type="submit" value="CONTINUE ">
</form>
My code to try to login (m_name, m_password, m_uriLogin all set
elsewhere):

ASCIIEncoding encoding = new ASCIIEncoding() ;
string postData = "name=" + m_name + "&password= " + m_password;
byte[] data = encoding.GetByt es(postData);

HttpWebRequest req = (HttpWebRequest )WebRequest.Cre ate(m_uriLogin) ;
req.Method = "POST";
req.ContentType = "applicatio n/x-www-form-urlencoded";
req.ContentLeng th = data.Length;
Stream newStream = req.GetRequestS tream();

newStream.Write (data, 0, data.Length);
newStream.Flush ();
newStream.Close ();

HttpWebResponse resp = (HttpWebRespons e)req.GetRespon se();

Stream istrm = resp.GetRespons eStream();
StreamReader sr = new StreamReader(is trm);
TxtReport.Appen dText(sr.ReadTo End()); // TxtReport is a text box

Jan 10 '06 #2
Nicholas Paldino [.NET/C# MVP] wrote:
beaker,

The cookie issue is most likely it. HTTP is a stateless protocol. What
you have to do on the HttpWebRequest is to use the CookieContainer property
to set the cookies for the request.

The thing is, once you log in, you will receive cookies back (and there
could possibly be one on your system already from the site, which you might
have to send). You have to take the cookies from the response and feed them
into the next request.

Hope this helps.


Thanks.

If I'm reading you right, are you suggesting

* create CookieContainer for the initial request
* save and use the cookies (returned after initial request) for further
requests?

I've just tried that, but I'm not receiving any cookies back in the
response....

(You were right, there is already a cookie my Cookies folder, but I
don't want to use this as hopefully I can share this app with other people).

Thanks.
Jan 10 '06 #3
beaker,

Well, you can call WinInet API functions through the P/Invoke layer to
get the information about that cookie if you wanted. This would allow you
to distribute your app as well.

The thing to understand about web apps is that there are a good number
of variables that it can use to process the request and produce a result.
Usually, it can be something like cookies, but it can also be other things,
like the referrer field, the user agent, etc, etc.

You might want to get a sniffer (such as Fiddler, which is a free tool
from MS, I believe), which you can use to sniff the requests being sent to
the website. This way, you can tailor the HttpWebRequest to do what you
want.

Also, you should be using more using statements to dispose of items in
your code correctly (streams, readers, the response).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"beaker" <ra************ **@rhubarbblahb lah.net> wrote in message
news:iC******** ************@fe 1.news.blueyond er.co.uk...
Nicholas Paldino [.NET/C# MVP] wrote:
beaker,

The cookie issue is most likely it. HTTP is a stateless protocol.
What you have to do on the HttpWebRequest is to use the CookieContainer
property to set the cookies for the request.

The thing is, once you log in, you will receive cookies back (and
there could possibly be one on your system already from the site, which
you might have to send). You have to take the cookies from the response
and feed them into the next request.

Hope this helps.


Thanks.

If I'm reading you right, are you suggesting

* create CookieContainer for the initial request
* save and use the cookies (returned after initial request) for further
requests?

I've just tried that, but I'm not receiving any cookies back in the
response....

(You were right, there is already a cookie my Cookies folder, but I don't
want to use this as hopefully I can share this app with other people).

Thanks.

Jan 10 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1679
by: Neil Benn | last post by:
Hello, I'm running a test and having issues with logging, if I call logging.shutdown() and then want to start the logging going again then I get a problem as if I call shutdown, I can't get the root logger again, such as : ..>>> import logging ..>>> objTestLogger = logging.getLogger() ..>>> objTestLogger.setLevel(logging.INFO)
1
3670
by: jjesso | last post by:
I am trying to add a new logging level. logging.config.fileConfig("bengineLog.cfg") logging.CLIENT = logging.INFO + 1 logging.addLevelName( logging.CLIENT, 'CLIENT' ) logging.root.setLevel( ) logger = logging.getLogger(None) logging.Logger.client('test') I get error:
2
3111
by: Tor Erik Sønvisen | last post by:
Hi Have the following code: import logging logging.basicConfig(level = logging.DEBUG, format = ' %(message)s', filename = 'rfs.log', filemode = 'w')
0
395
by: Karuppasamy | last post by:
H I am trying to use the Logging Module provided by Microsoft Application Blocks for .Net I installed everything as per the Instructions given in the 'Development Using the Logging Block' But when i am trying to run the sample, i am getting the following error in the Event Viwer Kindly help me on this
6
7322
by: pmatos | last post by:
Hi all, I am trying to create a simple but efficient C++ logging class. I know there are lots of them out there but I want something simple and efficient. The number one requirement is the possibility of shutting logging down at compile time and suffer no performance penalty whatsoever for getting logging on whenever I wish. Of course that I would need to recompile the project each time I want to turn logging on or off. But given a...
23
2219
by: Rotem | last post by:
Hi, while working on something in my current project I have made several improvements to the logging package in Python, two of them are worth mentioning: 1. addition of a logging record field %(function)s, which results in the name of the entity which logged the record. My version even deduces the class name in the case which the logger is a bound method, and assuming the name of the "self" variable is indeed "self".
0
1862
by: robert | last post by:
As more and more python packages are starting to use the bloomy (Java-ish) 'logging' module in a mood of responsibility and as I am not overly happy with the current "thickener" style of usage, I want to put this comment and a alternative most simple default framework for discussion. Maybe there are more Python users which like to see that imported (managed) logging issue more down-to-earth and flexible ? ... Vinay Sajip wrote: >...
7
3033
by: djc | last post by:
I see many ways to accomplish setting up proxy settings for a web request in the documentation but many of them are marked as obsolete. 1) What is the current and correct way to tell all my httpWebRequests within a class to *not* use any proxy server? I don't want to setup the proxy on each webRequest within my class on an individual basis, and I don't want to rely on the bypassLocal setting, or the host exclusion list since I don't...
3
1122
by: philwilks | last post by:
I have a dedicated server on which I run several ASP.Net 2.0 website. At the moment, each site has an Application_OnError subroutine that is defined in the site's Global.asax file. This writes the error to a log file, as well as emailing me with an alert. Is there a better way to do this? Ideally, I'd just have one thing set up that would pick up errors from any of my websites. I was thinking that there might be a way to use the Windows...
0
8930
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8766
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9428
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4536
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4799
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3244
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2699
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2171
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.