473,785 Members | 2,235 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

WebRequest : execute a button

Hello,

I tried to execute a button on an aspx webpage using WebRequest, but it
failed.
When posting data as if I did a login (see code), I just receive the
login page, instead of the page I should get after login.
The button I tried to 'push' (by adding &login=Login in de posted data,
where login is the name of the login button - I verified this data by
capturing the data of a request using a webbrowser) has not executed.

This is how I proceeded :

- First I requested the webpage in the standard way when you use
WebRequest :

string uri = @"http://localhost/Login.aspx";
WebRequest req = WebRequest.Crea te(uri);
WebResponse response = req.GetResponse ();
Stream respstream = response.GetRes ponseStream();
StreamReader reader = new StreamReader(re spstream, Encoding.ASCII) ;
string resphtml = reader.ReadToEn d();

- From the response I used regex to obtain the viewstate that I will
use in the second request where I just want to push a button on the
loginpage :

string html = resphtml.Replac e("\n", " ");
Regex r = new Regex("<input[\\t ]+type=\"hidden\ "[\\t
]+name=\"__VIEWS TATE\" value=\"(?<view state>[^\"]+)\"");
Match m = r.Match(html);
string viewstate = "";
if (m.Success) { viewstate = m.Groups["viewstate"].Value; }

- I prepare the string I will post; notice "login=Logi n" by which I
pushed the button. I also did an url encoding (space to +, strange
chars to %xx) :

string requeststr =
string.Format(" __VIEWSTATE={0} &name=myname&pw d=notofyourbusi ness&login=Logi n",viewstate );
string requrlencoded = UrlEncoder.Enco de(requeststr);

- Then a do a POST with the data in requeststr you see a little higher
:

req = WebRequest.Crea te(uri);
req.Method = "POST";
req.ContentType = "applicatio n/x-www-form-urlencoded";
byte[] encodedBytes = Encoding.UTF8.G etBytes(requrle ncoded);
req.ContentLeng th = encodedBytes.Le ngth;

Stream requestStream = req.GetRequestS tream();
requestStream.W rite(encodedByt es, 0, encodedBytes.Le ngth);
requestStream.C lose();

response = req.GetResponse ();
respstream = response.GetRes ponseStream();
reader = new StreamReader(re spstream, Encoding.ASCII) ;
resphtml = reader.ReadToEn d();
respstream.Clos e();
response.Close( );

I also tried it with new objects, instead of reusing the objects of the
first request (same result).

Instead of executing the login button I just receive the login page
again, as if I requested that page without the POSTed data.

Has anyone tried something similar or has anybody suggestions about
what I did wrong ?

Thanks for any help,

Paul

Nov 17 '05 #1
4 4324
Paul,

Do you have access to the code for the site you are trying to access?
It might be easier for you to expose a web service from that website, and
consume it in your code. The amount of code that you are using which is
dependent on things you shouldn't have to deal with (parsing viewstate out
of the page, for instance) is staggering.

Exposing a web service, if possible, would be a much, much better
solution.

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

"Paul" <pa************ *@hotmail.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
Hello,

I tried to execute a button on an aspx webpage using WebRequest, but it
failed.
When posting data as if I did a login (see code), I just receive the
login page, instead of the page I should get after login.
The button I tried to 'push' (by adding &login=Login in de posted data,
where login is the name of the login button - I verified this data by
capturing the data of a request using a webbrowser) has not executed.

This is how I proceeded :

- First I requested the webpage in the standard way when you use
WebRequest :

string uri = @"http://localhost/Login.aspx";
WebRequest req = WebRequest.Crea te(uri);
WebResponse response = req.GetResponse ();
Stream respstream = response.GetRes ponseStream();
StreamReader reader = new StreamReader(re spstream, Encoding.ASCII) ;
string resphtml = reader.ReadToEn d();

- From the response I used regex to obtain the viewstate that I will
use in the second request where I just want to push a button on the
loginpage :

string html = resphtml.Replac e("\n", " ");
Regex r = new Regex("<input[\\t ]+type=\"hidden\ "[\\t
]+name=\"__VIEWS TATE\" value=\"(?<view state>[^\"]+)\"");
Match m = r.Match(html);
string viewstate = "";
if (m.Success) { viewstate = m.Groups["viewstate"].Value; }

- I prepare the string I will post; notice "login=Logi n" by which I
pushed the button. I also did an url encoding (space to +, strange
chars to %xx) :

string requeststr =
string.Format(" __VIEWSTATE={0} &name=myname&pw d=notofyourbusi ness&login=Logi n",viewstate );
string requrlencoded = UrlEncoder.Enco de(requeststr);

- Then a do a POST with the data in requeststr you see a little higher
:

req = WebRequest.Crea te(uri);
req.Method = "POST";
req.ContentType = "applicatio n/x-www-form-urlencoded";
byte[] encodedBytes = Encoding.UTF8.G etBytes(requrle ncoded);
req.ContentLeng th = encodedBytes.Le ngth;

Stream requestStream = req.GetRequestS tream();
requestStream.W rite(encodedByt es, 0, encodedBytes.Le ngth);
requestStream.C lose();

response = req.GetResponse ();
respstream = response.GetRes ponseStream();
reader = new StreamReader(re spstream, Encoding.ASCII) ;
resphtml = reader.ReadToEn d();
respstream.Clos e();
response.Close( );

I also tried it with new objects, instead of reusing the objects of the
first request (same result).

Instead of executing the login button I just receive the login page
again, as if I requested that page without the POSTed data.

Has anyone tried something similar or has anybody suggestions about
what I did wrong ?

Thanks for any help,

Paul

Nov 17 '05 #2
you don't urlencode the postdata, you urlencode each value

string.Format(" __VIEWSTATE={0} &name={1}&pwd={ 2}&login=Login" ,
UrlEncoder.Enco de(viewstate),
UrlEncoder.Enco de(name),
UrlEncoder.Enco de(pwd))

you don't want the "&" and "=" delimiters encoded. no special chars are
allowed in a value name.

note: the leading "__" in VIEWSTATE is a violation of W3C standards. don't
follow ms's example in your own field names.

-- bruce (sqlwork.com)
"Paul" <pa************ *@hotmail.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
Hello,

I tried to execute a button on an aspx webpage using WebRequest, but it
failed.
When posting data as if I did a login (see code), I just receive the
login page, instead of the page I should get after login.
The button I tried to 'push' (by adding &login=Login in de posted data,
where login is the name of the login button - I verified this data by
capturing the data of a request using a webbrowser) has not executed.

This is how I proceeded :

- First I requested the webpage in the standard way when you use
WebRequest :

string uri = @"http://localhost/Login.aspx";
WebRequest req = WebRequest.Crea te(uri);
WebResponse response = req.GetResponse ();
Stream respstream = response.GetRes ponseStream();
StreamReader reader = new StreamReader(re spstream, Encoding.ASCII) ;
string resphtml = reader.ReadToEn d();

- From the response I used regex to obtain the viewstate that I will
use in the second request where I just want to push a button on the
loginpage :

string html = resphtml.Replac e("\n", " ");
Regex r = new Regex("<input[\\t ]+type=\"hidden\ "[\\t
]+name=\"__VIEWS TATE\" value=\"(?<view state>[^\"]+)\"");
Match m = r.Match(html);
string viewstate = "";
if (m.Success) { viewstate = m.Groups["viewstate"].Value; }

- I prepare the string I will post; notice "login=Logi n" by which I
pushed the button. I also did an url encoding (space to +, strange
chars to %xx) :

string requeststr =
string.Format(" __VIEWSTATE={0} &name=myname&pw d=notofyourbusi ness&login=Logi n",viewstate );
string requrlencoded = UrlEncoder.Enco de(requeststr);

- Then a do a POST with the data in requeststr you see a little higher
:

req = WebRequest.Crea te(uri);
req.Method = "POST";
req.ContentType = "applicatio n/x-www-form-urlencoded";
byte[] encodedBytes = Encoding.UTF8.G etBytes(requrle ncoded);
req.ContentLeng th = encodedBytes.Le ngth;

Stream requestStream = req.GetRequestS tream();
requestStream.W rite(encodedByt es, 0, encodedBytes.Le ngth);
requestStream.C lose();

response = req.GetResponse ();
respstream = response.GetRes ponseStream();
reader = new StreamReader(re spstream, Encoding.ASCII) ;
resphtml = reader.ReadToEn d();
respstream.Clos e();
response.Close( );

I also tried it with new objects, instead of reusing the objects of the
first request (same result).

Instead of executing the login button I just receive the login page
again, as if I requested that page without the POSTed data.

Has anyone tried something similar or has anybody suggestions about
what I did wrong ?

Thanks for any help,

Paul

Nov 17 '05 #3
Paul wrote:
Hello,

I tried to execute a button on an aspx webpage using WebRequest, but
it failed.
When posting data as if I did a login (see code), I just receive the
login page, instead of the page I should get after login.
The button I tried to 'push' (by adding &login=Login in de posted
data, where login is the name of the login button - I verified this
data by capturing the data of a request using a webbrowser) has not
executed.

This is how I proceeded :

- First I requested the webpage in the standard way when you use
WebRequest :

string uri = @"http://localhost/Login.aspx";
WebRequest req = WebRequest.Crea te(uri);
WebResponse response = req.GetResponse ();
Stream respstream = response.GetRes ponseStream();
StreamReader reader = new StreamReader(re spstream, Encoding.ASCII) ;
string resphtml = reader.ReadToEn d();

- From the response I used regex to obtain the viewstate that I will
use in the second request where I just want to push a button on the
loginpage :

string html = resphtml.Replac e("\n", " ");
Regex r = new Regex("<input[\\t ]+type=\"hidden\ "[\\t
]+name=\"__VIEWS TATE\" value=\"(?<view state>[^\"]+)\"");
Match m = r.Match(html);
string viewstate = "";
if (m.Success) { viewstate = m.Groups["viewstate"].Value; }

- I prepare the string I will post; notice "login=Logi n" by which I
pushed the button. I also did an url encoding (space to +, strange
chars to %xx) :

string requeststr =
string.Format(" __VIEWSTATE={0} &name=myname&pw d=notofyourbusi ness&login
=Login",viewsta te); string requrlencoded =
UrlEncoder.Enco de(requeststr);
As Bruce already pointed out, that's not going to work. You have to
encode all values of the query string individually, unless UrlEncoder
is meant to be a non BCL class which handles entire strings (unlike
HttpUtility.Url Encode()).
- Then a do a POST with the data in requeststr you see a little higher
:

req = WebRequest.Crea te(uri);
req.Method = "POST";
req.ContentType = "applicatio n/x-www-form-urlencoded";
byte[] encodedBytes = Encoding.UTF8.G etBytes(requrle ncoded);
req.ContentLeng th = encodedBytes.Le ngth;

Stream requestStream = req.GetRequestS tream();
requestStream.W rite(encodedByt es, 0, encodedBytes.Le ngth);
requestStream.C lose();

response = req.GetResponse ();
respstream = response.GetRes ponseStream();
reader = new StreamReader(re spstream, Encoding.ASCII) ;
resphtml = reader.ReadToEn d();
respstream.Clos e();
response.Close( );

I also tried it with new objects, instead of reusing the objects of
the first request (same result).
You confuse objects with variables. For the sencond request, you reuse
your local variables, but have a new HttpWebRequest, a new
HttpWebResponse , and a new StreamReader.
Instead of executing the login button I just receive the login page
again, as if I requested that page without the POSTed data.

Has anyone tried something similar or has anybody suggestions about
what I did wrong ?


You're missing session management. Add a CookieContainer instance to
your HttpWebRequest to allow for cookie management and use it
throughout your session.

Cheers,
--
http://www.joergjooss.de
mailto:ne****** **@joergjooss.d e
Nov 17 '05 #4
Thanks everybody !
The problem was the urlencode indeed.

Paul

Nov 17 '05 #5

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

Similar topics

3
6351
by: Paul | last post by:
Hello, First I want to refer to the problem "WebRequest : execute a button" of a few days ago. The way I solved it, I loose my session, and as a consequence my session variables. I don't want to keep those variables, as an alternative, as ViewState variables because I don't want to transfer to many hidden fields. This is the code I use :
1
1954
by: Sujith Jagini | last post by:
------------------------------------------------------------------ <input type="hidden" name="__VIEWSTATE" value="dDwtMTUzMzQ4ODY4ODs7Pleb3NLElxrFpPbkFWoEst9bdqIM" /> <span id="Label1" style="height:27px;width:764px;Z-INDEX: 101; LEFT: 27px; POSITION: absolute; TOP: 110px">Label</span> <input name="url" type="text" id="url" style="height:25px;width:276px;Z-INDEX: 102; LEFT: 20px; POSITION: absolute; TOP: 18px" /> <input type="submit"...
2
3969
by: Stephen Miller | last post by:
I have an ASPX report and I want to capture the rendered HTML and write to a file on the webserver. Several posts suggest using WebRequest to make a second call to the page, and screen-scrape the resulting HTML. The technique typically described is: '-- Get the current URL and request page Dim url As String = System.Web.HttpContext.Current.Request.Url.AbsoluteUri Dim req As System.Net.WebRequest = System.Net.WebRequest.Create(url)
4
1443
by: Paul | last post by:
Hello, I tried to execute a button on an aspx webpage using WebRequest, but it failed. When posting data as if I did a login (see code), I just receive the login page, instead of the page I should get after login. The button I tried to 'push' (by adding &login=Login in de posted data, where login is the name of the login button - I verified this data by capturing the data of a request using a webbrowser) has not executed.
0
1153
by: Frank S. | last post by:
Hello, when I try to execute a web request from a .NET client application through a proxy, the server returns a 401 (not authorized) error message. It works when i bypass the proxy or when i try the same from the Internet Explorer. Any idea how to solve this problem. I tried already several code variants : Dim wrGETURL As System.Net.WebRequest
6
1714
by: matt | last post by:
hello, i am having trouble doing something. when a user triggers a certain event in my app, i need to initiate another web request to one of my other webpages, programmatically. currently, i do this via a WebRequest -- i attach the default credentials and get the response stream. that part works. like so: WebRequest request = HttpWebRequest.Create(reportAspxURL); request.Credentials = CredentialCache.DefaultCredentials;
10
1789
by: Steve | last post by:
I am trying to create a downloader which will bypass the saveas box in the WebBrowser control. I have the file downloading, but I don't know what the filename is that is being passed through the stream. Is their a way to determine what the file name is so that I can execute the appropriate functionality of the extensions. The stream is created dynamically so I cannot capture the filename straight from the URL. Thanks STeve
6
10010
by: Jack | last post by:
I have a WebRequest object that I use to log into a site and then post some XML. In doing this I set the KeepAlive = true so that it maintains the connection and does operates undo the initial login. Is there a way to force this connection to close after I an done with it. What happens is that I may need to post the XML in several chunks due to size therefore I cannot set the KeepAlive to False when I post the XML and the way the code...
0
1033
by: CodeMedic42 | last post by:
I have started to play with connecting to a .Net web service that I created. I wanted to figure out how to dynamicaly connect to it without creating a web reference to it. I have so far been able to connect to it and execute a method with the following signature,... public string Execute(string command) What I want to do now is call a method with the following signature,.. public string Execute(string command, out string...
0
9646
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
9484
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
10350
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...
0
10157
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10097
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9957
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
4055
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
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
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.