获取HttpWebRequest的GetResponse()给出ProtocolViolationException

本文关键字:给出 ProtocolViolationException GetResponse HttpWebRequest 获取 | 更新日期: 2023-09-27 18:10:48

我尝试向谷歌页面发出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;
        }

谁能指出我的错误?提前感谢!

获取HttpWebRequest的GetResponse()给出ProtocolViolationException

您试图写入响应流。您应该写入请求流,然后获得响应:

using (Stream stream = req.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}
using (HttpWebResponse response = (HttpWebResponse) req.GetResponse())
{
    return response.Cookies;
}
相关文章: