【问题标题】:Getting GetResponse() of HttpWebRequest gives ProtocolViolationException获取 HttpWebRequest 的 GetResponse() 会给出 ProtocolViolationException
【发布时间】:2011-10-06 18:39:34
【问题描述】:

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

        }

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

【问题讨论】:

    标签: c# .net httpwebrequest


    【解决方案1】:

    您正在尝试写入响应流。您应该写入 request 流,然后得到响应:

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

    【讨论】:

    • 你好,约翰!感谢您的回答。第一个问题已解决,但现在我从请求响应中收到其他错误:The remote server returned an error: (405) Method Not Allowed.。我究竟做错了什么?另一个问题:谷歌有一个简单的API,不使用Oauth autentication 协议?这是因为我正在编写一个桌面应用程序。我需要处理 orkut 页面。
    • @Kakashi:很抱歉没有看到您之前的回复。我不知道,恐怕 - 我从来没有使用过这个 API。即使我为 Google 工作,请不要将我的任何 cmets 视为“来自”Google :) 您确定不应该使用完整的“ServiceLoginAuth”网址而不仅仅是 accounts.google.com 吗?跨度>
    • 很晚,但对于任何寻找“不允许的方法”的人来说,就是这样。您访问的 API 不支持该方法。例如,当它只接受 GET 时,您尝试发布,反之亦然。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 2013-07-23
    • 2017-12-29
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多