获取HttpWebRequest的GetResponse()会产生ProtocolViolationException

时间:2011-10-06 18:39:35

标签: c# .net httpwebrequest

我尝试向谷歌页面发出http请求,但是当我尝试获取响应时它不起作用并提供ProtocolViolationException

这是我的代码:

 public CookieCollection GetTempCookies()
        {

            CookieContainer MyCookieContainer = new CookieContainer();
            CookieCollection cookies = GetGalxAndGaps();
            string postData = "foo=baa&etc.."; 
            byte[] data = Encoding.ASCII.GetBytes(postData);
            int postLength = data.Length;

            for (int i = 0, max = cookies.Count; i != max; i++)
            {
                Cookie tempCookie = cookies[i];
                Cookie cookie = new Cookie(tempCookie.Name, tempCookie.Value, tempCookie.Path);
                MyCookieContainer.Add(new Uri("https://accounts.google.com/ServiceLoginAuth"), cookie);
            }

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://accounts.google.com");
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = postLength;
            req.AllowAutoRedirect = false;
            req.CookieContainer = MyCookieContainer;

            HttpWebResponse response = (HttpWebResponse)req.GetResponse(); // <- this cause the exception 
            Stream stream = response.GetResponseStream();
            stream.Write(data, 0, postLength);
            return response.Cookies;

        }

有人可以指出我的错误吗? 提前谢谢!

1 个答案:

答案 0 :(得分:2)

您正在尝试响应流。您应该写入请求流,然后获取响应:

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

using (HttpWebResponse response = (HttpWebResponse) req.GetResponse())
{
    return response.Cookies;
}