Search code examples
c#htmlhttpwebrequest

simulate a web form button click using C# HttpWebRequest


I'm trying to send a post request to simulate pressing a button that resides on a webpage form using C# HTMLWebRequest. The form on the webpage looks like the following:

        <form method="post" action="HtmlAdaptor">
        <input type="hidden" name="action" value="invokeOp">
        <input type="hidden" name="name" 
          value='somevalue'>
        <input type="hidden" name="methodIndex" value="5">
        <hr align='left' width='80'>
        <h4>java.util.List methodName()</h4>
        <p>MBean Operation.</p>

        <input type="submit" value="Invoke">
        </form>

My code to send the HTML post and read HTML response:

string webURL = "http://pageurl";
HttpWebRequest myRequest =(HttpWebRequest)WebRequest.Create(webURL);
myRequest.Method = "POST";
        byte[] lbPostBuffer = System.Text.Encoding.GetEncoding(1252).GetBytes(sb.ToString());
        myRequest.ContentType = "text/xml; charset=utf-8";
        myRequest.ContentLength = lbPostBuffer.Length;
        myRequest.Accept = "text/xml";

        Stream loPostData = myRequest.GetRequestStream();
        loPostData.Write(lbPostBuffer, 0, lbPostBuffer.Length);
        loPostData.Close();
        HttpWebResponse loWebResponse = (HttpWebResponse)myRequest.GetResponse();
        Encoding enc = System.Text.Encoding.GetEncoding(1252);
        StreamReader loResponseStream = new StreamReader(loWebResponse.GetResponseStream(), enc);
        string lcHtml = loResponseStream.ReadToEnd();

        loWebResponse.Close();

        loResponseStream.Close();

I have a string builder variable "sb" that gets converted to a byte array to be posted to the site. My problem is I'm not sure what I should be sending in the sb.ToString() to submit the invoke button on that form.


Solution

  • I've found the format of the request by using fiddler.