Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HttpWebRequest to POST to a form on an outside server

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".

like image 430
alpheus Avatar asked Jan 26 '10 00:01

alpheus


2 Answers

You want to read the Response stream:

using (var resp = myRequest.GetResponse())
{
    using (var responseStream = resp.GetResponseStream())
    {
        using (var responseReader = new StreamReader(responseStream))
        {
        }
    }
}
like image 160
John Saunders Avatar answered Oct 12 '22 22:10

John Saunders


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(response.GetResponseStream()))
    {
        result = reader.ReadToEnd();
    }
}
like image 25
Daniel Vassallo Avatar answered Oct 13 '22 00:10

Daniel Vassallo