36

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.

Community
  • 1
  • 1
JC.
  • 11,561
  • 11
  • 41
  • 50

6 Answers6

32

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;
   } 
shanabus
  • 12,989
  • 6
  • 52
  • 78
  • 1
    The 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. Aug 13 '09 at 19:45
  • 1
    @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 http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=32254 – Kurt Schindler Aug 13 '09 at 22:04
  • The 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. – JC. Aug 14 '09 at 00:34
  • Side 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. – ZombieCode Oct 29 '14 at 18:21
13

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.

Jeff Meatball Yang
  • 37,839
  • 27
  • 91
  • 125
  • This does not get the same response as I do when I use the browser directly. – JC. Aug 13 '09 at 20:14
  • 4
    Your 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. – Jeff Meatball Yang Aug 13 '09 at 20:24
5

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>

*/
Sklivvz
  • 30,601
  • 24
  • 116
  • 172
2
Response.Write("<script> try {this.submit();} catch(e){} </script>");
Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
DRiVe
  • 29
  • 1
2

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);
        }
JDPeckham
  • 2,414
  • 2
  • 23
  • 26
1

I had a similar issue in MVC (which lead me to this problem).

I am receiving a FORM as a string response from a WebClient.UploadValues() request, which I then have to submit - so I can't use a second WebClient or HttpWebRequest. This request returned the string.

using (WebClient client = new WebClient())
  {
    byte[] response = client.UploadValues(urlToCall, "POST", new NameValueCollection()
    {
        { "test", "value123" }
    });

    result = System.Text.Encoding.UTF8.GetString(response);
  }

My solution, which could be used to solve the OP, is to append a Javascript auto submit to the end of the code, and then using @Html.Raw() to render it on a Razor page.

result += "<script>self.document.forms[0].submit()</script>";
someModel.rawHTML = result;
return View(someModel);

Razor Code:

@model SomeModel

@{
    Layout = null;
}

@Html.Raw(@Model.rawHTML)

I hope this can help anyone who finds themselves in the same situation.