如何在使用 C# 发帖时获取 cookie

发布于 2025-01-13 15:39:30 字数 1070 浏览 1 评论 0原文

下面是用于获取 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许久 2025-01-20 15:39:30

此链接可能可以帮助您如何发出 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文