Using HttpWebRequest for POST in form on an external server

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

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

+7
source share
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)) { } } } 
+8
source
 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(); } } 
+2
source

All Articles