[转载]C#如何通过Socket的方式获取httponly cookie – Orangutan – 博客园.
正常情况下C#可以使用HttpWebRequest、HttpWebResponse和CookieContainer类来获取Cookie,但 是当Cookie设置为httponly,我们就不能用上面的方法获取。这时候可以用Socket来模拟http提交。具体如下:
1.先取得默认DNS服务器地址:
IPEndPoint endPoint; IPAddress IpList; IpList = Dns.GetHostAddresses( "www.7fenx.com" )[0]; |
2.模拟http请求,设置http头:
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.发送请求
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.获取服务器的返回信息
Byte[] byteReceive = new Byte[1024]; Int32 bytes = socket.Receive(byteReceive); string str = Encoding.Default.GetString(byteReceive, 0, bytes); |
5.提取Cookie内容
Regex rgxCookie = new Regex( "Set-Cookie:.*" ); MatchCollection cookies = rgxCookie.Matches(cookie); |
提取后需要做的就是解析Cookie就是一些字符串的处理。
附上网络编程基础知识地址:
http://www.7fenx.com/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.html
初接触网络编程,如果哪里说错请指出。
欢迎加我QQ交流:1780242721,请注明:“博客园”
本文如需转载请注明出处。