views:

324

answers:

2

I am trying to simulate a POST to a form on an external server that does not require any authentication, and capture a sting containing the resulting page. This is the first time I have done this so I am looking for some help with what I have so far. This is what the form looks like:

<FORM METHOD="POST" ACTION="/controller" NAME="GIN">
<INPUT type="hidden" name="JSPName" value="GIN">

Field1:
<INPUT type="text" name="Field1" size="30"
                maxlength="60" class="txtNormal" value=""> 

</FORM>

This is what my code looks like:

    ASCIIEncoding encoding = new ASCIIEncoding();
    string postData = "Field1=VALUE1&JSPName=GIN";
    byte[] data = encoding.GetBytes(postData);
    // Prepare web request...
    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://XXX/controller");
    myRequest.Method = "POST";
    myRequest.ContentType = "text/html";
    myRequest.ContentLength = data.Length;
    Stream newStream = myRequest.GetRequestStream();
    // Send the data.
    newStream.Write(data, 0, data.Length);

    StreamReader reader = new StreamReader(newStream);
    string text = reader.ReadToEnd(); 

    MessageBox.Show(text);

    newStream.Close();

Currently, the code returns "Stream was not readable".

+4  A: 

You want to read the Response stream:

using (var resp = myRequest.GetResponse())
{
    using (var responseStream = resp.GetResponseStream())
    {
        using (var responseReader = new StreamReader(responseStream))
        {
        }
    }

}
John Saunders
Bah, beat me to it ;)
jvenema
Considering his rep, I think he beats a lot of people to it.
John K
+1  A: 
ASCIIEncoding encoding = new ASCIIEncoding();

string postData = "Field1=VALUE1&JSPName=GIN";
byte[] data = encoding.GetBytes(postData);

// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://XXX/");
myRequest.Method = "POST";
myRequest.ContentType = "text/html";
myRequest.ContentLength = data.Length;

string result;

using (WebResponse response = myRequest.GetResponse())
{
    using (var reader = new StreamReader(myRequest.GetResponseStream()))
    {
        result = reader.ReadToEnd();
    }
}
Daniel Vassallo