c# - 获取 HttpWebRequest 的 GetResponse() 会给出 ProtocolViolationException

标签 c# .net httpwebrequest

我尝试向 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;

        }

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

最佳答案

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

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

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

关于c# - 获取 HttpWebRequest 的 GetResponse() 会给出 ProtocolViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7678916/

相关文章:

c# - url 中带有子目录的 Response.Redirect

IOS - 重新建立连接时对要发送的请求进行排队的最佳方式

c# - 服务定位器困惑

c# - 使用 "greater than or equals"或仅使用 "greater than"

c# - 交叉继承实现与EF Core 3.0

.net - 在 Crystal Report 2008 中使用 .net 对象作为数据源

c# - 对于复杂的搜索查询,Google 搜索返回 503 错误

c# - 如何在 C# 中将 SSL 证书与 HttpWebRequest 一起使用?

c# - 有什么好的理由写东西 "backwards",例如: if ("some_text" == var_name)?

c# - 使用 Roslyn 查找对方法的所有引用