当使用C#.Net(像爬虫)浏览网站的页面时,我需要保留相同的会话ID.我发现了一些方法,http嗅探器非常方便,比较我的IE浏览器发送的内容(HTTP请求)和从Web服务器接收(HTTP响应),因为重要信息在标题中(未显示)通过浏览器).请不要在服务器到浏览器之间公开的会话ID和服务器代码私有的服务器会话变量(如php)之间混淆.
WebHeaderCollection headerCollection = new WebHeaderCollection();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
/* save headers */
for (int i = 0; i < response.Headers.Count; i++)
{
headerCollection.Add(response.Headers.AllKeys[i], response.Headers.Get(i));
}
/* save cookies */
cookieContainer = new CookieContainer();
foreach (Cookie cookie in response.Cookies)
{
cookieContainer.Add(cookie);
}
}
Run Code Online (Sandbox Code Playgroud)
发出其他GET或POST请求:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
...
/* restore PHPSESSID */
for (int i = 0; i < headerCollection.Count; i++)
{
string key = headerCollection.GetKey(i);
if (key == "Set-Cookie")
{
key = "Cookie";
}
else …Run Code Online (Sandbox Code Playgroud)