开发者

Getting GetResponse() of HttpWebRequest gives ProtocolViolationException

开发者 https://www.devze.com 2023-04-11 20:01 出处:网络
I\'m tried make an http request to google page,but it not works and give an ProtocolViolationException when I try get the Response.

I'm tried make an http request to google page,but it not works and give an ProtocolViolationException when I try get the Response.

Here's my code:

 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.CookieContaine开发者_开发百科r = MyCookieContainer;

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

        }

Can someone point my error? Thanks in advance!


You're trying to write to the response stream. You should write to the request stream, and then get the response:

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

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

精彩评论

暂无评论...
验证码 换一张
取 消