How to submit http form using C#
Solution 1
Here is a sample script that I recently used in a Gateway POST transaction that receives a GET response. Are you using this in a custom C# form? Whatever your purpose, just replace the String fields (username, password, etc.) with the parameters from your form.
private String readHtmlPage(string url)
{
//setup some variables
String username = "demo";
String password = "password";
String firstname = "John";
String lastname = "Smith";
//setup some variables end
String result = "";
String strPost = "username="+username+"&password="+password+"&firstname="+firstname+"&lastname="+lastname;
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally {
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()) )
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}
Solution 2
Your HTML file is not going to interact with C# directly, but you can write some C# to behave as if it were the HTML file.
For example: there is a class called System.Net.WebClient with simple methods:
using System.Net;
using System.Collections.Specialized;
...
using(WebClient client = new WebClient()) {
NameValueCollection vals = new NameValueCollection();
vals.Add("test", "test string");
client.UploadValues("http://www.someurl.com/page.php", vals);
}
For more documentation and features, refer to the MSDN page.
Solution 3
You can use the HttpWebRequest class to do so.
Example here:
using System;
using System.Net;
using System.Text;
using System.IO;
public class Test
{
// Specify the URL to receive the request.
public static void Main (string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);
// Set some reasonable limits on resources used by this request
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
// Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Console.WriteLine ("Content length is {0}", response.ContentLength);
Console.WriteLine ("Content type is {0}", response.ContentType);
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream ();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
Console.WriteLine ("Response stream received.");
Console.WriteLine (readStream.ReadToEnd ());
response.Close ();
readStream.Close ();
}
}
/*
The output from this example will vary depending on the value passed into Main
but will be similar to the following:
Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>
*/
Solution 4
I needed to have a button handler that created a form post to another application within the client's browser. I landed on this question but didn't see an answer that suited my scenario. This is what I came up with:
protected void Button1_Click(object sender, EventArgs e)
{
var formPostText = @"<html><body><div>
<form method=""POST"" action=""OtherLogin.aspx"" name=""frm2Post"">
<input type=""hidden"" name=""field1"" value=""" + TextBox1.Text + @""" />
<input type=""hidden"" name=""field2"" value=""" + TextBox2.Text + @""" />
</form></div><script type=""text/javascript"">document.frm2Post.submit();</script></body></html>
";
Response.Write(formPostText);
}
Solution 5
Response.Write("<script> try {this.submit();} catch(e){} </script>");
JC.
Updated on July 09, 2022Comments
-
JC. almost 2 years
I have a simple html file such as
<form action="http://www.someurl.com/page.php" method="POST"> <input type="text" name="test"><br/> <input type="submit" name="submit"> </form>
Edit: I may not have been clear enough with the question
I want to write C# code which submits this form in the exact same manner that would occur had I pasted the above html into a file, opened it with IE and submitted it with the browser.
-
JC. almost 15 yearsNo, this just sends a URL. I'm asking how to programmatically construct and submit a form.
-
JC. almost 15 yearsThe page I'm submitting to does not get the information if I use this code. It only works when using the html snippet I referenced.
-
JC. almost 15 yearsThis does not get the same response as I do when I use the browser directly.
-
Jeff Meatball Yang almost 15 yearsYour browser sends a bunch of headers. Sniff the HTTP request that your browser sends using Fiddler or Firebug. Then replicate these headers by using the client.Headers property.
-
Kurt Schindler almost 15 years@JC: why exactly does this solution not work? You're not getting your "test" input value? I just went to solve this on my own after seeing all of these unaccepted answers only to find out I did it exactly the same shanabus did it. HttpWebRequest is indeed the solution if you are looking to programmatically POST to a form. See this post for another example essentially doing the same thing csharpfriends.com/Forums/ShowPost.aspx?PostID=32254
-
JC. almost 15 yearsThe page I submit to sends a response based on the input. It only sends the right response if I do this through the browser. Maybe it has to do with the php implementation, I don't know. Or as mentioned below, I may need to add the right headers.
-
Sklivvz almost 15 yearsThis also does POSTs (See WebRequest.Method)
-
ZombieCode over 9 yearsSide Note: I had to add a "?" to the beginning of my string of variables (typical character for all URL passed variables) to get the connection to work.
-
Null511 about 5 yearsAs @JC said, this only answers how to send a POST request; it does not answer how to construct the form in the HTTP request.