jerp
jerp

Reputation: 257

visual studio c# interact with website

I want to make an application that can interact with an existing website. The website has some search related text box fields that a user usually types stuff into and then clicks a button to go the next page. I'd like to automate this process by making a visual studio c# application. I'm not sure where to start, it seems like most tutorials out there are geared towards creating your own website that does stuff, not interacting with an existing one.

As far as I can tell, typing into the search and clicking the button doesn't seem to create a unique URL string (not like Google maps does), because the URL doesn't change when it take me to the search results. I'm not sure what type of TCP commands I need to send (I know about "GET", but that's about it).

Any pointers?

Upvotes: 3

Views: 2632

Answers (1)

bytecode77
bytecode77

Reputation: 14840

Entering text into the URL would be a GET request. TCP is just the underlying protocol beneath HTTP.

What you're looking for is a HTTP POST request.

Start with WebRequest.

// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();

the postData variable contains the elements that you want to "insert" into the text boxes. It should give you a good start on this. I've been using this technique for all projects which involve website interaction.

Selenium which was suggested in the comments could be an option, only if you don't mind that a specific browser needs to be installed, as it utilizes it for this purpose. It's not a good solution if you want to deploy your application.

Upvotes: 1

Related Questions