无法使用HttpWebResponse流实例化StreamReader - System.ArgumentException:Stream无法读取

时间:2018-01-29 13:02:41

标签: c# httpwebrequest streamreader httpwebresponse

我很久没有在这里发帖了,如果我没有正确格式化这个问题,请原谅我。我试图通过.NET对象HttpWebRequest和HttpWebResponse登录到一个网站(省略)。使用Wireshark,当我通过我的应用程序登录本网站时,我可以看到我的POST请求与Chrome的POST请求相同。我有问题得到了完整的回复。

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

此响应对象具有所有相应的响应标头,但我仍希望看到通过HTTP分块响应发送的数据。我也可以在Wireshark中验证这一点。我的理解是我需要实例化一个StreamReader对象来读取剩余的数据。我的代码在这条线上爆炸了:

using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))

堆栈跟踪显示此错误:

  

System.ArgumentException:Stream无法读取。

如何在发送POST请求后使用此StreamReader对象读取整个响应?下面是我的代码,它发送登录到网站的POST请求。如果您有任何问题,请告诉我,我很乐意澄清任何疑惑。

public bool Login()
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://WEBSITE-REMOVED/CheckAccess");
        request.CookieContainer = CookieContainer;

        //Set POST data.
        string postData = "institution=AAA";
        postData += "&ismobile=false";
        postData += "&id=BBB";
        postData += "&password=CCC";
        byte[] data = Encoding.ASCII.GetBytes(postData);

        //Configure HTTP POST request.
        request.Headers.Clear();
        request.Method = "POST";
        request.Accept = @"text/html, application/xhtml+xml, image/jxr, */*";
        request.Referer = @"http://WEBSITE-REMOVED/entry.html";
        request.Headers.Add("Accept-Language", "en-US");
        request.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko";
        request.ContentType = @"application/x-www-form-urlencoded";
        request.Headers.Add("Accept-Encoding", "gzip, deflate");
        request.Host = "op.responsive.net";
        request.ContentLength = data.Length;
        request.KeepAlive = true;
        request.Headers.Add("Cache-Control", "no-cache");

        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }//using

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        {
            //TO-DO
        }
    }//try
    catch(Exception ex)
    {
        File.AppendAllText(ErrorLogDirectory + "Errors.txt", "Login() Exception\r\n" + System.DateTime.Now + "\r\n" + ex.ToString() + Environment.NewLine);
    }//catch

    return false;
}//Login

0 个答案:

没有答案