我想知道可以直接使用HttpWebRequest、HttpWebResponse可以获取到带有httpOnly的cookie吗?
如果可以的话,该怎么写呢?
在获取属性为httpOnly的cookie时候 直接使用HttpWebRequest、HttpWebResponse好像获取不到,我看了网上是这么说的(如下),都说要用socket来获取,如果照这么说,那么使用HttpWebRequest来进行POST跟GET遇到带有httpOnly的cookie岂不要切换成scoket来写吗?
[C#] 纯文本查看 复制代码 正常情况下C#可以使用HttpWebRequest、HttpWebResponse和CookieContainer类来获取Cookie,但是当Cookie设置为httponly,我们就不能用上面的方法获取。这时候可以用Socket来模拟http提交。具体如下:
1.先取得默认DNS服务器地址:
*.cs
IPEndPoint endPoint;
IPAddress IpList;
IpList = Dns.GetHostAddresses("www.7fenx.com")[0];
2.模拟http请求,设置http头:
*.cs
StringBuilder sendString=new StringBuilder(200);
sendString.Append("POST "+ "/" + " HTTP/1.1\r\n");
sendString.Append("Accept: */*\r\n");
sendString.Append("Host: "+host+"\r\n");
sendString.Append("User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36\r\n");
sendString.Append("Content-Type: application/x-www-form-urlencoded\r\n");
sendString.Append("Content-Length: "+sendData.Length+"\r\n");
sendString.Append("Connection: keep-alive\r\n\r\n");
sendString.Append(postData+"\r\n");
3.发送请求
*.cs
byte[] sendBytes = Encoding.GetEncoding(endcoding).GetBytes(sendString.ToString());
int httpPoint = 80;
endPoint = new IPEndPoint(ip, httpPoint);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(endPoint);
socket.Send(sendBytes,sendBytes.Length,0);
4.获取服务器的返回信息
*.cs
Byte[] byteReceive = new Byte[1024];
Int32 bytes = socket.Receive(byteReceive);
string str = Encoding.Default.GetString(byteReceive, 0, bytes);
5.提取Cookie内容
*.cs
Regex rgxCookie = new Regex("Set-Cookie:.*");
MatchCollection cookies = rgxCookie.Matches(cookie);
提取后需要做的就是解析Cookie就是一些字符串的处理。
|