473,795 Members | 2,512 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

submit form via HttpWebRequest or WebClient

has anyone successfully used HttpWebRequest or WebClient class to simulate
submission of a simple HTML form?

for example: a very simple plain-vanilla form with a textbox and a button.
when the button is clicked the form is submitted with the textbox contents.

could you please post some sample code? thanks.
Nov 18 '05 #1
14 12143
John A Grandy wrote:
has anyone successfully used HttpWebRequest or WebClient class to
simulate submission of a simple HTML form?

for example: a very simple plain-vanilla form with a textbox and a
button. when the button is clicked the form is submitted with the
textbox contents.

could you please post some sample code? thanks.


That's a full blown WebRequest/WebResponse sample including URL encoding.
public void PostForm(string url, string formData, string encodingName) {
// URL encode the post data, applying the character encoding given by
// encodingName.
MemoryStream content = new MemoryStream(fo rmData.Length * 2);
Encoding encoding = Encoding.GetEnc oding(encodingN ame);
string[] keyValuePairs = formData.Split( '&', '=');
int numberOfPairs = keyValuePairs.L ength;
bool isKey = true;
foreach (string keyValue in keyValuePairs) {
byte[] bytes = HttpUtility.Url EncodeToBytes(k eyValue, encoding);
content.Write(b ytes, 0, bytes.Length);
if (isKey) {
content.WriteBy te((byte) '=');
}
else {
content.WriteBy te((byte) '&');
}
isKey = !isKey;
}
// We'll end up with one surplus '&' -- shouldn't hurt, but we cut it
anyway
content.SetLeng th(content.Leng th - 1);

// That's the actual HTTP part of the sample
HttpWebRequest request = (HttpWebRequest ) WebRequest.Crea te(url);
request.Method = "POST";
request.Content Type = String.Format(
"applicatio n/x-www-form-urlencoded; charset={0}", encodingName);
request.Content Length = content.Length;
using (Stream requestStream = request.GetRequ estStream()) {
content.WriteTo (requestStream) ;
}

HttpWebResponse response = (HttpWebRespons e) request.GetResp onse();
using (Stream responseStream = response.GetRes ponseStream()) {
byte[] buffer = new byte[response.Conten tLength];
responseStream. Read(buffer, 0, buffer.Length);
// Process buffer... e.g. write to file, decode to string, etc.
}
}

Cheers,

--
Joerg Jooss
jo*********@gmx .net
Nov 18 '05 #2
Hi John:

I have an example here:

Screen Scraping, ViewState, and Authentication using ASP.Net
http://odetocode.com/Articles/162.aspx

This also shows how to extract the viewstate out of an asp.net page to
post back.

HTH,

--
Scott
http://www.OdeToCode.com

On Mon, 23 Aug 2004 23:23:31 -0700, "John A Grandy"
<johnagrandy-at-yahoo.com> wrote:
has anyone successfully used HttpWebRequest or WebClient class to simulate
submission of a simple HTML form?

for example: a very simple plain-vanilla form with a textbox and a button.
when the button is clicked the form is submitted with the textbox contents.

could you please post some sample code? thanks.


Nov 18 '05 #3
so whatever data the user would enter into the text box "textbox1", i
simulate by composing the string

formData="textb ox1=thedata"

but how do i know what encodingName should be ?
"Joerg Jooss" <jo*********@gm x.net> wrote in message
news:ua******** ******@tk2msftn gp13.phx.gbl...
John A Grandy wrote:
has anyone successfully used HttpWebRequest or WebClient class to
simulate submission of a simple HTML form?

for example: a very simple plain-vanilla form with a textbox and a
button. when the button is clicked the form is submitted with the
textbox contents.

could you please post some sample code? thanks.


That's a full blown WebRequest/WebResponse sample including URL encoding.
public void PostForm(string url, string formData, string encodingName) {
// URL encode the post data, applying the character encoding given by
// encodingName.
MemoryStream content = new MemoryStream(fo rmData.Length * 2);
Encoding encoding = Encoding.GetEnc oding(encodingN ame);
string[] keyValuePairs = formData.Split( '&', '=');
int numberOfPairs = keyValuePairs.L ength;
bool isKey = true;
foreach (string keyValue in keyValuePairs) {
byte[] bytes = HttpUtility.Url EncodeToBytes(k eyValue, encoding);
content.Write(b ytes, 0, bytes.Length);
if (isKey) {
content.WriteBy te((byte) '=');
}
else {
content.WriteBy te((byte) '&');
}
isKey = !isKey;
}
// We'll end up with one surplus '&' -- shouldn't hurt, but we cut it
anyway
content.SetLeng th(content.Leng th - 1);

// That's the actual HTTP part of the sample
HttpWebRequest request = (HttpWebRequest ) WebRequest.Crea te(url);
request.Method = "POST";
request.Content Type = String.Format(
"applicatio n/x-www-form-urlencoded; charset={0}", encodingName);
request.Content Length = content.Length;
using (Stream requestStream = request.GetRequ estStream()) {
content.WriteTo (requestStream) ;
}

HttpWebResponse response = (HttpWebRespons e) request.GetResp onse();
using (Stream responseStream = response.GetRes ponseStream()) {
byte[] buffer = new byte[response.Conten tLength];
responseStream. Read(buffer, 0, buffer.Length);
// Process buffer... e.g. write to file, decode to string, etc.
}
}

Cheers,

--
Joerg Jooss
jo*********@gmx .net

Nov 18 '05 #4
John A Grandy wrote:
so whatever data the user would enter into the text box "textbox1", i
simulate by composing the string

formData="textb ox1=thedata"
Right.
but how do i know what encodingName should be ?


That's the tricky part, because this depends on the web application. But
there's a simple heuristic that should work for most sites. Use the same
encoding that the site uses as character encoding. Open the web page and
check out what character encoding your browser applies (in IE
View->Encoding). Western Europe (ISO) is ISO-8859-1, whereas Western Europe
(Windows) is Windows-1252. Unicoded (UTF-8) is, um, UTF-8 ;->

Unless you're working with a non US or non Western European web site, those
are the ones you'll most likely encounter. In case of doubt, use ISO-8859-1.

Cheers,

--
Joerg Jooss
jo*********@gmx .net
Nov 18 '05 #5
very interesting ....

unfortunately, i'm in a stickier situation than communicating with a
public-facing website.

i'm communicating over vpn with a private web-server meant for
data-provision to intermediaries.

the web-server does not validate credentials. it just immediately returns
data (interesting, as an xml doc)

the only working tool i have is a java applet written by someone else
(someone who is long gone).

the java applet is very simple. just a textbox and a submit button.

a long alphanumeric string is entered into the textbox (it ends with "^").

clicking the button fires a js function that calls form.submit and the form
is posted.

"view source" on the IE browseer hosting the java applet reveals only a very
simple block of html

a <textarea> element is used for data-entry.

i can't disclose the actual url -- but its similar to
"https://www.somecompany .com:5555/someservice.asm x/somefunction"

.... so apparently the web-server is hosting a .net web-service.
i tried your method. i constructed using the data-string successfully used
in the Java applet :

postData = "myTextArea=dat aString";

encodingName = "utf-8";

request.GetResp onse();

triggered a runtime error : "500 : internal server error"
do you think the problem might be with encodingName? what do you think
good possibilities are ?

or could the problem be in some other area ?

"Joerg Jooss" <jo*********@gm x.net> wrote in message
news:en******** ******@TK2MSFTN GP09.phx.gbl...
John A Grandy wrote:
so whatever data the user would enter into the text box "textbox1", i
simulate by composing the string

formData="textb ox1=thedata"
Right.
but how do i know what encodingName should be ?


That's the tricky part, because this depends on the web application. But
there's a simple heuristic that should work for most sites. Use the same
encoding that the site uses as character encoding. Open the web page and
check out what character encoding your browser applies (in IE
View->Encoding). Western Europe (ISO) is ISO-8859-1, whereas Western

Europe (Windows) is Windows-1252. Unicoded (UTF-8) is, um, UTF-8 ;->

Unless you're working with a non US or non Western European web site, those are the ones you'll most likely encounter. In case of doubt, use ISO-8859-1.
Cheers,

--
Joerg Jooss
jo*********@gmx .net

Nov 18 '05 #6
also, the MSDN docs for Encoding.GetEnc oding(name) do not list "ISO-8859-1"

"Joerg Jooss" <jo*********@gm x.net> wrote in message
news:en******** ******@TK2MSFTN GP09.phx.gbl...
John A Grandy wrote:
so whatever data the user would enter into the text box "textbox1", i
simulate by composing the string

formData="textb ox1=thedata"
Right.
but how do i know what encodingName should be ?


That's the tricky part, because this depends on the web application. But
there's a simple heuristic that should work for most sites. Use the same
encoding that the site uses as character encoding. Open the web page and
check out what character encoding your browser applies (in IE
View->Encoding). Western Europe (ISO) is ISO-8859-1, whereas Western

Europe (Windows) is Windows-1252. Unicoded (UTF-8) is, um, UTF-8 ;->

Unless you're working with a non US or non Western European web site, those are the ones you'll most likely encounter. In case of doubt, use ISO-8859-1.
Cheers,

--
Joerg Jooss
jo*********@gmx .net

Nov 18 '05 #7
John A Grandy wrote:
also, the MSDN docs for Encoding.GetEnc oding(name) do not list
"ISO-8859-1"


They just show a few names in the .NET docs. The list of all supported
encodings is hidden deeply within MSDN, and of course it's at some place
you'd never expect it to be ;-)

Start here:

http://www.microsoft.com/globaldev/g..._codepage.mspx

Cheers,

--
Joerg Jooss
jo*********@gmx .net
Nov 18 '05 #8
John A Grandy wrote:
very interesting ....

unfortunately, i'm in a stickier situation than communicating with a
public-facing website. [...] i can't disclose the actual url -- but its similar to
"https://www.somecompany .com:5555/someservice.asm x/somefunction"

... so apparently the web-server is hosting a .net web-service.
Yes.
i tried your method. i constructed using the data-string
successfully used in the Java applet :

postData = "myTextArea=dat aString";

encodingName = "utf-8";

request.GetResp onse();

triggered a runtime error : "500 : internal server error"
do you think the problem might be with encodingName? what do you
think good possibilities are ?

or could the problem be in some other area ?


I guess the whole approrach could be wrong then. My sample code showed a
programmatic web form submission, but you probably need a SOAP client.
Actually, if it is a "proper" Web Service, VS .NET should be able to
generate the necessary client-side code for you. The test code you've posted
doesn't fit into the picture at all, though.

I guess you'll need to talk to the Web Service guys to find out what
requests their web service can handle.

Cheers,

--
Joerg Jooss
jo*********@gmx .net
Nov 18 '05 #9
Hi Joerg ....

I don't think the approach you suggested is wrong.

I have a simple HTML page that submits its form to the web-server, and
successfully receives a response. The HTML form odes not communicate in any
way with any entity other than the following:

The JavaScript function triggered by the button click is very very simple :
all is does is a form.submit. There is no other client-side functionality
occurring.

Whatever method this company is using to process information on their side ,
they do accept posting of a simple form with

"InputData=0123 456789abcdefghi jklmnopqrstuvwx yz^" (for example)

Is there any problem with URL encoding the "^" character?

I think the encoding-type is probably the villian. I'll have to try various
possibilities.

Also, do you know various common headers that could be added? I see in
many of the postings to this newsgroup that quite a different number of
headers are being used.

"Joerg Jooss" <jo*********@gm x.net> wrote in message
news:uf******** ******@TK2MSFTN GP11.phx.gbl...
John A Grandy wrote:
very interesting ....

unfortunately, i'm in a stickier situation than communicating with a
public-facing website. [...]
i can't disclose the actual url -- but its similar to
"https://www.somecompany .com:5555/someservice.asm x/somefunction"

... so apparently the web-server is hosting a .net web-service.


Yes.
i tried your method. i constructed using the data-string
successfully used in the Java applet :

postData = "myTextArea=dat aString";

encodingName = "utf-8";

request.GetResp onse();

triggered a runtime error : "500 : internal server error"
do you think the problem might be with encodingName? what do you
think good possibilities are ?

or could the problem be in some other area ?


I guess the whole approrach could be wrong then. My sample code showed a
programmatic web form submission, but you probably need a SOAP client.
Actually, if it is a "proper" Web Service, VS .NET should be able to
generate the necessary client-side code for you. The test code you've

posted doesn't fit into the picture at all, though.

I guess you'll need to talk to the Web Service guys to find out what
requests their web service can handle.

Cheers,

--
Joerg Jooss
jo*********@gmx .net

Nov 18 '05 #10

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

Similar topics

4
520
by: Brent | last post by:
Hi, I want to build an app (C#, windows app, or web app, shouldn't make a difference) that submits an address to the canada post website's address lookup and then scrape the postal code out of the resulting page. Here is their page. http://www.canadapost.ca/tools/pcl/bin/advanced-e.asp It uses a form post. I would like a basic rundown of how to submit my own info into their results page (post), and then scrape out the info I need....
10
19362
by: Gregory A Greenman | last post by:
I'm trying to write a program in vb.net to automate filling out a series of forms on a website. There are three forms I need to fill out in sequence. The first one is urlencoded. My program is able to fill that one out just fine. The second form is multipart/form-data. Unfortunately, I haven't been able to fill that out in a way that makes the server happy. I set up a copy of this form at my web site so that I could see exactly what a...
5
60916
by: Darran | last post by:
Hi I want to be able to retrieve the data from a given URL, fill in the necessary form fields and submit the form back to the server, all from within a Windows Application. I can retrieve the HTML from the page, using the HttpWebRequest class but that is where I have become stuck. These are the remaining items I would like to be able to do 1 Fill in the necessary fields on the form. 2 Submit the data back to the server
1
11940
by: Jason Manfield | last post by:
What is the difference (pros and cons) between retrieving data from the web using System.Web.WebClient and using HttpWebRequest and Response to get the data? The WebClient download methods seem to neatly encapsulate the multiple steps (request.Create; request.GetResponse; response.GetResponseStream ...) required with the traditional HttpWebRequest/Response approach. I am trying to crawl urls and download data.
1
1236
by: Steve Klett | last post by:
Hello- I would like to implement something like what is covered in this article: http://www.netomatix.com/HttpPostData.aspx It shows how to post a form programtically vs with an actual form from a web page. Basically, I will have a desktop application that will post a form to an ..aspx page.
0
1470
by: natzol | last post by:
Hello, I need to provide the ability to post file and some form elements via our website (asp.net) to the third party website (asp page). On http://aspalliance.com/236#Page4 - I found great advices but still having troubles... it might some obvious error that I am making but I just dont see it. ==================FIRST - Webclient=================================
4
12712
by: Natalia | last post by:
Hello, I need to provide the ability to post file and some form elements via our website (asp.net) to the third party website (asp page). On http://aspalliance.com/236#Page4 - I found great advices but still having troubles... it might some obvious error that I am making but I just dont see it. ==================FIRST - Webclient=================================
12
7987
by: Mark Rae | last post by:
Hi, The following code works: HttpWebRequest objRequest = null; try { HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com"); using (HttpWebResponse objResponse =
1
3709
by: ERobishaw | last post by:
Using Winform app writing a HTTP Post using the following... on the server side, I get no form fields. Request.Form.AllKeys.Length = 0. If I put the field/value paris in the URL I can use Request to retrieve the values, but POST doesn't work. There is NO Proxy... the only thing I can think is that ASP.NET is somehow filtering out the page because I'm obviously not posting the viewstate??? Seems like there was some setting for this,...
0
9519
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
10438
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
10214
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...
0
10001
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...
0
9042
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6780
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
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...
1
4113
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
3727
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.