8

我正在尝试在不需要任何身份验证的外部服务器上模拟 POST 到表单,并捕获包含结果页面的字符串。这是我第一次这样做,所以我正在寻找一些关于我目前所拥有的帮助。这是表单的样子:

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

这就是我的代码的样子:

    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();

目前,代码返回“流不可读”。

4

2 回答 2

9

您想阅读响应流:

using (var resp = myRequest.GetResponse())
{
    using (var responseStream = resp.GetResponseStream())
    {
        using (var responseReader = new StreamReader(responseStream))
        {
        }
    }
}
于 2010-01-26T00:47:25.090 回答
2
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();
    }
}
于 2010-01-26T00:50:14.333 回答