【发布时间】:2015-09-16 17:24:11
【问题描述】:
我正在尝试登录我经常访问的网站中的 Ajax 聊天室。我希望创建一个适度的机器人,但我对 cookie 处理很感兴趣。我已经搜索了该网站上的所有问题,但所有解决方案似乎都在做我正在做的事情,即将HttpWebRequest 的CookieContainer 参数设置为cc。 CookieContainer 会填充数据,但此数据不会与 HttpWebRequest 一起发送。我的代码如下所示。
class Program
{
static config populated_config;
static void Main(string[] args)
{
#region config
StreamReader sr = new StreamReader(File.Open("config.xml", FileMode.Open), Encoding.UTF8);
XmlSerializer xmls = new XmlSerializer(typeof(config));
populated_config = (config)xmls.Deserialize(sr);
#endregion
#region login
//retrieve default cookies
CookieContainer cc = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(populated_config.domain + "chat/");
request.CookieContainer = cc;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string login_info = "login=login&redirect=http%3A%2F%2F"+WebUtility.UrlEncode(populated_config.domain)+"%2Fchat%2F%3FchannelName%3DPublic&username=" + WebUtility.UrlEncode(populated_config.username) + "&password=" + WebUtility.UrlEncode(populated_config.password) + "&channelName=Public&lang=en&submit=Login";
request = (HttpWebRequest)WebRequest.Create(populated_config.domain + "ucp.php?mode=login");
request.CookieContainer = cc;
request.Method = "POST";
StreamWriter sw = new StreamWriter(request.GetRequestStream());
sw.Write(login_info);
response = (HttpWebResponse)request.GetResponse();
string sid = findCookieValue(cc, "phpbb3_jznvi_sid");
request = (HttpWebRequest)WebRequest.Create(populated_config.domain + "chat/?channelName=Public&sid=" + sid);
request.CookieContainer = cc;
request.Method = "GET";
response = (HttpWebResponse)request.GetResponse();
#endregion
}
public static string findCookieValue(CookieContainer cc,string cookieName)
{
foreach (Cookie cookie in cc.GetCookies(new Uri(populated_config.domain)))
if (cookie.Name == cookieName)
return cookie.Value;
return null;
}
}
在不自己手动制作标头的情况下,如何使用HttpWebRequest 发送 cookie,我做错了什么?
【问题讨论】:
标签: c# ajax cookies httpwebrequest