Using HttpWebRequest to POST to a form on an outsi

2019-04-06 21:28发布

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

2条回答
2楼-- · 2019-04-06 21:56
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();
    }
}
查看更多
迷人小祖宗
3楼-- · 2019-04-06 22:05

You want to read the Response stream:

using (var resp = myRequest.GetResponse())
{
    using (var responseStream = resp.GetResponseStream())
    {
        using (var responseReader = new StreamReader(responseStream))
        {
        }
    }
}
查看更多
登录 后发表回答