如何在使用 C# 发帖时获取 cookie
下面是用于获取 cookie 的 python 代码,它按预期工作,并尝试将其转换为 C# 但未获取 cookie。 我可以通过任何其他方式将下面的 Python 代码转换为相应的 C# 代码。
Python代码:
data = {"login": user, "password": password}
response = session.post(url, headers=HTTP_HEADERS, data=data, verify = False)
response.raise_for_status()
result = session.cookies.get("auth_session")
C#代码
CookieContainer Cookies = new CookieContainer();
String username = "xxx_priceyyy";
String password = "xxxx@6781119";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
HttpWebRequest oRequest = WebRequest.Create("https://kube.xxx.com/") as HttpWebRequest;
oRequest.CookieContainer = Cookies;
oRequest.Method = "POST";
oRequest.KeepAlive = false;
oRequest.Headers.Add("Authorization", "Basic " + encoded);
Stream newStream = oRequest.GetRequestStream();
WebResponse oResponse = oRequest.GetResponse();
var responseString = new StreamReader(oResponse.GetResponseStream()).ReadToEnd();
Below is the python code for getting cookies and it is worked as expected, and trying to convert this to C# but not getting the cookies.
Any other way i can convert below Python code to respective C# code.
Python code:
data = {"login": user, "password": password}
response = session.post(url, headers=HTTP_HEADERS, data=data, verify = False)
response.raise_for_status()
result = session.cookies.get("auth_session")
C# code
CookieContainer Cookies = new CookieContainer();
String username = "xxx_priceyyy";
String password = "xxxx@6781119";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
HttpWebRequest oRequest = WebRequest.Create("https://kube.xxx.com/") as HttpWebRequest;
oRequest.CookieContainer = Cookies;
oRequest.Method = "POST";
oRequest.KeepAlive = false;
oRequest.Headers.Add("Authorization", "Basic " + encoded);
Stream newStream = oRequest.GetRequestStream();
WebResponse oResponse = oRequest.GetResponse();
var responseString = new StreamReader(oResponse.GetResponseStream()).ReadToEnd();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此链接可能可以帮助您如何发出 HTTP POST Web 请求。
值得特别注意的是,推荐使用 httpClient 而不是 WebRequest 的方法。
This link might be able to help you How to make an HTTP POST web request.
The recommended method of using httpClient over WebRequest is of particular note.