gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:19 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com