
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
886
|
Chapter 16: Networking
16.3 Simulating Form Execution
Problem
You need to send a collection of name-value pairs to simulate a form being executed
on a browser to a location identified by a URL.
Solution
Use the System.Net.WebClient class to send a set of name-value pairs to the web
server using the
UploadValues method. This class enables you to masquerade as the
browser executing a form by setting up the name-value pairs with the input data.
The input field ID is the name, and the value to use in the field is the value:
using System;
using System.Net;
using System.Text;
using System.Collections.Specialized;
Uri uri = new Uri("http://localhost/FormSim/WebForm1.aspx");
WebClient client = new WebClient( );
// Create a series of name-value pairs to send.
NameValueCollection collection = new NameValueCollection( );
// Add necessary parameter-value pairs to the name-value container.
collection.Add("Identity","foo@bar.com");
collection.Add("Item","Books");
collection.Add("Quantity","5");
Console.WriteLine("Uploading name/value pairs to URI {0} ...",
uri.AbsoluteUri);
// Upload the NameValueCollection.
byte[] responseArray =
client.UploadValues(uri.AbsoluteUri,"POST",collection);
// Decode and display the response.
Console.WriteLine("\nResponse received was {0}",
Encoding.ASCII.GetString(responseArray)); ...