Fake a form submission with C# WebClient - c#

I need to call a web and retrieve the resulting data from the model in my asp.net mvc application. When accessed on the web, the form looks like this:
<form id="textEntryForm" name="textEntryForm" method="post" action="/project/evaluate_to_pdf">
<textarea id="p" rows="20" name="p" cols="132"/><br/>
<input type="button" value="parse" name="do_parse" onclick="new Ajax.Updater('parsedProject','/project/parse',{asynchronous:true,evalScripts:true,on404:function(e){alert('not found!')},parameters:Form.serialize(this.form)});return false"/>
<input type="button" value="evaluate_to_html" name="do_evaluate_to_html" onclick="new Ajax.Updater('parsedProject','/project/evaluate_to_html',{asynchronous:true,evalScripts:true,on404:function(e){alert('not found!')},parameters:Form.serialize(this.form)});return false"/>
<input type="button" value="evaluate" name="do_evaluate" onclick="new Ajax.Updater('parsedProject','/project/evaluate',{asynchronous:true,evalScripts:true,on404:function(e){alert('not found!')},parameters:Form.serialize(this.form)});return false"/>
<input type="button" value="evaluate to pdf source" name="do_evaluate_to_pdf_source" onclick="new Ajax.Updater('parsedProject','/project/evaluate_to_pdf_source',{asynchronous:true,evalScripts:true,on404:function(e){alert('not found!')},parameters:Form.serialize(this.form)});return false"/>
<input type="submit" id="do_evaluate_to_pdf" value="evaluate_to_pdf" name="do_evaluate_to_pdf"/>
</form>
I need to pass the data that would be entered into textarea id="p". How do add that in, using a WebClient to connect?
Thanks!
Edit This isn't for testing purposes, I need to retrieve the data for use in my application.

I just used this: http://www.eggheadcafe.com/community/aspnet/2/69261/you-can-use-the-webclient.aspx

Another option is the Lightweight Test Automation Framework by Microsoft <- Here Steve Sanderson applies it to MVC.
(source: codeville.net)
(source: codeville.net)

You create a Stream and pass it into your HttpWebRequest.
// 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 = "p=Some text here from the textarea";
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 ();
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

These things have a habit of becoming more and more complex, for example should you need to handle cookies, authentication or multipart form uploads for uploading files etc. I suggest using curl (http://sourceforge.net/projects/libcurl-net/)

Something like this:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string data = "&p=" + dataThatNeedsToBeInTextArea;
byte[] byteArray = Encoding.UTF8.GetBytes (data);
req.ContentLength = byteArray.Length;
Stream stream= req.GetRequestStream ();
stream.Write (byteArray, 0, byteArray.Length);
stream.Close ();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string response = streamIn.ReadToEnd();
streamIn .Close();

Agreeing with #wentbackward, WatiN is another alternative.

Related

Post data to a open URL without landing on the page c# asp.net

I am working on a site that sends data to another website and it has a landing page with a URL by using. The issue is I do not want to do the REdirect I just want it to send data to that page and continue with the code under it.
The other Site doesn't have API's how can I do this?
I have been looking at examples all of them are referring to API url's with log-in authentication but this URL does not require a log in just send in the data with the URL(www.example.come/submit?Firstname=Firstname;LastName=LastName;)
Something like that without actually redirecting the page to that site.
You can use the 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 ();
You can read more about this Here

Proper Way to open this URL in a C# app

I have a URL that I want to open in my C# app. This URL is used to talk to a communications device, not an internet web site. I have gotten by (I think) all the cert stuff. But the text I get back in the program IS NOT the same thing that CORRECTLY displays when I use a web browser.
Here's the code.
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Web;
namespace VMLConnStatus
{
class Program
{
static void Main(string[] args)
{
System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();
// Create a request for the URL: https://192.168.30.15/cgi-bin/connstatus?202
String url = "https://192.168.30.15/cgi-bin/";
String data = "connstatus?202";
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = data;
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();
Console.ReadLine();
}
}
public class MyPolicy : ICertificatePolicy
{
public bool CheckValidationResult(ServicePoint srvPoint,
X509Certificate certificate, WebRequest request,
int certificateProblem)
{
//Return True to force the certificate to be accepted.
return true;
}
}
}
The result, though not perfectly displayed in Chrome, should be:
NA NA NA NA 4c:cc:34:02:6d:26 00:23:A7:24:A3:B6
But the text I get in the console window is:
Ok
<HTML>
<HEAD><TITLE>Index of cgi-bin/</TITLE></HEAD>
<BODY BGCOLOR="#99cc99" TEXT="#000000" LINK="#2020ff" VLINK="#4040cc">
<H4>Index of cgi-bin/</H4>
<PRE>
. 15Jun2014 09:48
0
.. 15Jun2014 09:48
0
connstatus 15Jun2014 09:48
19580
firmwarecfg 15Jun2014 09:48
45736
webcm 15Jun2014 09:48
23836
</PRE>
<HR>
<ADDRESS><A HREF="http://www.acme.com/software/mini_httpd/">mini_httpd/1.19 19de
c2003</A></ADDRESS>
</BODY>
</HTML>
Not EVEN close to the same thing.
What am I doing wrong?
Chuck
UPDATE: Code changed. URL, GET, and request writing (presuming I understood the directions). New code is:
static void Main(string[] args)
{
System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();
// Create a request for the URL: https://192.168.30.15/cgi-bin/connstatus?202
String url = "https://192.168.30.15/cgi-bin/connstatus?202";
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "GET";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Get the request stream.
//Now it throws an exception here--------------------------------
//"Cannot send a content-body with this verb-type."
Stream dataStream = request.GetRequestStream();
// 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();
Console.ReadLine();
}
You are using http method POST but the url you have in the comment looks more like GET so then you probably need WebRequest.Create(url + data).
The incorrect response is the index page for https://192.168.30.15/cgi-bin/ which if you put into Chrome will give you the same "wrong" response.
You might not need to write any data to the request stream and can change the Method and ContentType for the request.
The solution required two parts.
First, doing the proper things, thus a total code rework.
I had the dreaded "The server committed a protocol violation. Section=ResponseHeader Detail=Header name is invalid". I tried to make the programatic solution for this work, but it is a .NET 2.0 solution and I was not able to figure it out in .NET4+. So, I edited the .config file and went on.
Here's the final code:
//Initialization
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(#"https://192.168.30.15/cgi-bin/connstatus?202");
//method is GET.
WebReq.Method = "GET";
//Get the response handle
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//read the response
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
//display it
Console.WriteLine(_Answer.ReadToEnd());
//pause for the ENTER key
Console.ReadLine();
This was added to the .config file in the debug folder (and would be added in the Release folder also..... using VS2013)
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing = "true"/>
</settings>
</system.net>
Thank-you to everyone that replied. The inspiration helped me get to the solution.

it not sending text to website using webrequest

I want to programatically send data to a website and then programatically click submit button. This is the HTML code I'm trying to fill up:
<textarea id="rpslBox:postRpsl:rpslObject" name="rpslBox:postRpsl:rpslObject" class="ripe-input-field ui-corner-all" rows="18" style="width:500px;"></textarea>
I'm using this C# code:
WebRequest request = WebRequest.Create("https://apps.db.ripe.net/syncupdates/simple-rpsl.html ");
// Set the Method property of the request to POST.
request.Method = "POST";
string textarea = "text";
// Create POST data and convert it to a byte array.
string postData = string.Format("rpslBox:postRpsl:rpslObject{0}", textarea);
When I run this code it returns the HTML code of the page without sending this text. How can I send this text? Thanks for your help!
I can't test if this works, but from what I understand from msdn, is that following code will convert your postdata to bytedata and submit that to the webserver:
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 ();
And that afterwards following code can be used to read the new response from the webserver:
// 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 ();

Receive image from c# in php

I use this code to send an image from desktop application to a php file on server:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://example.com/img.php");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "hello";
byte[] byteArray = ImageToByte(image);//Encoding.UTF8.GetBytes (postData);
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 ();
What function should I use in php to receive the image file?
Since you're not forming standartized post, you'll need to read directly from php input.
file_get_contents("php://input");
Provided your C# code produces a valid post request, you should be able to fetch it from the global $_POST array in PHP.

Implementing OnSubmit with httpwebrequest

I am new to C# and just messing around with it myself, now, i have been trying to create a WinForm that can post some parameters in a webpage and do something something on the resultant webpage obtained. Now I have accomplished this on a page that uses POST method, But i am not able to do so with A webpage that has a html code like this :
<form method="post" action="test.asp" name=FrontPage_Form1 onsubmit="return FrontPage_Form1_Validator(this)">
<div align="center"><center><p>
<input name="name" size="8" maxlength=8><font color="#faebd7">---
Now i don't how How To implement this "ONSUBMIT" with HttpWebRequest..
This is my current Code :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://cbseresults.nic.in/aieee/cbseaieee.asp");
request.Method = "POST";
string r = "regno=" + rno.ToString();
Bytes = Encoding.UTF8.GetBytes(r);
request.ContentLength = Bytes.Length;
request.ContentType = "application/x-www-form-urlencoded";
RequestStream = request.GetRequestStream();
RequestStream.Write(Bytes, 0, Bytes.Length);
RequestStream.Close();
Response = (HttpWebResponse)request.GetResponse();
StreamReader ResponseStream = new StreamReader(Response.GetResponseStream(), Encoding.ASCII);
string Result = ResponseStream.ReadToEnd();
ResponseStream.Close();
But its not working, Any Help is greatly appreciated...
Try using Fiddler in order to understand what the page is sending and receiving from the server.
Then make the request as it is shown in fiddler...
You can also use WebClient to open some pages or sending and receiving data from server.
There are some ways to click on buttons or links:
Use a WebBrowser object in your app and Iterate through objects on the page by using SelectNextControl method of WebBrowser object and then sending Enter key like so: SendKeys.Send("{Enter}");
Using JavaScript and invoking functions and reading elements using getElementById and some other methods

Categories

Resources