他返回的cookies值就是 p3p CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV" 类似这个值, 我调试了下 . 返回值中的cookies值是0 你应该在headers 中拿
天涯登陆的时候,是分了好几步的。 第一步,登陆后,在返回页面里面通过js跳转第二步,第一次跳转的页面里面包含4个js链接,用来获取cookie,实现sso,在页面内部有通过js跳转到登陆用户首页第三步,通过上面页面包含的链接,获取各个域名的cookie 第四步,跳转到第二步页面中的用户首页 下面是我写的一个控制台代码(我只是获取了第三步的第一个域名的cookie,就是tianya.cn的,如果要获取所有四个域名的cookie,可以自己在下面的代码添加)using System; using System.IO; using System.Text; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates;namespace tianya { class Program { public static void Main(string[] args) { LoginTianYa(url, usr, pwd); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
namespace 900091
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
NameValueCollection myCol = new NameValueCollection();
System.Net.CookieContainer cookieJar = new System.Net.CookieContainer();
PostData("http://passport.tianya.cn/login", myCol, ref cookieJar);
}
public string PostData(string PostUrl, NameValueCollection nvc, ref CookieContainer cookCon)
{
string strResault = ""; string strPostUrl = PostUrl; string strPostData = ""; foreach (string ie in nvc)
{
strPostData += ie + "=" + nvc[ie] + "&";
}
if (strPostData.EndsWith("&"))
strPostData = strPostData.Substring(0, strPostData.Length - 1);
////数据生成结束
int ilen = strPostData.Length;
////构建Post包
try
{
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(strPostUrl);
System.Net.ServicePointManager.Expect100Continue = false;
httpReq.Method = "POST";
httpReq.CookieContainer = cookCon;
httpReq.Accept = "application/x-shockwave-flash, image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*";
// httpReq.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
httpReq.Referer = strPostUrl;
httpReq.ContentType = "application/x-www-form-urlencoded";
httpReq.Headers.Add("Accept-Language", "zh-cn");
//httpReq.Headers.Add("Accept-Encoding", "gzip, deflate");
httpReq.Headers.Add("Cache-Control", "no-cache");
httpReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6.5; .NET CLR 2.0.50727)"; byte[] bsInData = UTF8Encoding.UTF8.GetBytes(strPostData);
httpReq.ContentLength = bsInData.Length;
Stream inputStream = httpReq.GetRequestStream();
inputStream.Write(bsInData, 0, bsInData.Length);
inputStream.Close();
inputStream.Dispose(); HttpWebResponse httpRes = null;
httpRes = (HttpWebResponse)httpReq.GetResponse(); Stream outStream = httpRes.GetResponseStream();
StreamReader sr = new StreamReader(outStream, System.Text.Encoding.GetEncoding("utf-8")); strResault = sr.ReadToEnd(); int i = strResault.Length; sr.Close(); return strResault;
}
catch (Exception ex)
{
return "TimeOut:" + ex.Message;
}
}
}
}
另外你下面的代码不知道是做什么用的。既然你前面的BBSRequest.CookieContainer是空的,BBSRequest.CookieContainer.GetCookies自然也不会有什么值。
if (BBSResponse.Cookies.Count == 0)
{
BBSResponse.Cookies= BBSRequest.CookieContainer.GetCookies(BBSResponse.ResponseUri);
if (BBSResponse.Cookies.Count == 0)
{
BBSResponse.Cookies = GetUriCookieContainer(BBSResponse.ResponseUri).GetCookies(BBSResponse.ResponseUri);
}
}
我想代码里面的gCookieCollention应该是一个类的全局变量,它是每次请求后的BBSResponse.Cookies;,你在BBSRequest.CookieContainer =new CookieContainer();后加上BBSRequest.CookieContainer.Add(gCookieCollention)看一下
这是抓包的图,是不是没有Cookies返回呢,那要怎么做才有呀,通过谷歌浏览器登录查询都有的,为什么直接POST就没有呢,有没有办法让他有呢?
在非https 的情况下(很少用过). request.中的cookies值基本上都能拿到的. 没有天涯帐号.就不方便测试了.
CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV"
类似这个值,
我调试了下 . 返回值中的cookies值是0
你应该在headers 中拿
第一步,登陆后,在返回页面里面通过js跳转第二步,第一次跳转的页面里面包含4个js链接,用来获取cookie,实现sso,在页面内部有通过js跳转到登陆用户首页第三步,通过上面页面包含的链接,获取各个域名的cookie
第四步,跳转到第二步页面中的用户首页
下面是我写的一个控制台代码(我只是获取了第三步的第一个域名的cookie,就是tianya.cn的,如果要获取所有四个域名的cookie,可以自己在下面的代码添加)using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;namespace tianya
{
class Program
{
public static void Main(string[] args)
{
LoginTianYa(url, usr, pwd);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
static string url = "https://passport.tianya.cn/login";
static string usr = "用户名";
static string pwd = "密码";
static HttpWebRequest BBSRequest;
static HttpWebResponse BBSResponse;
static CookieCollection gCookieCollention = new CookieCollection();
public static void LoginTianYa(string url, string usr, string pwd)
{
string responseHTML = string.Empty; ;
//string loginstr = string.Format("fowardURL=http%3A%2F%2Fwww.tianya.cn%2F&vwriter={0}&vpassword={1}&rmflag=1&submit=+",usr,pwd);
string loginstr = string.Format("method=name&vwriter={0}&vpassword={1}&fowardURL=http%3A%2F%2Fwww.tianya.cn&returnURL=&from=&Submit=%E7%99%BB%E5%BD%95",usr,pwd);
byte[] replybyte = Encoding.UTF8.GetBytes(loginstr); try
{
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
BBSRequest = (HttpWebRequest)WebRequest.Create(url);
}
else
{
BBSRequest = (HttpWebRequest)WebRequest.Create(url);
}
PrepareRequest();
BBSRequest.Method = "POST";
BBSRequest.ContentType = "application/x-www-form-urlencoded";
BBSRequest.Referer = "http://passport.tianya.cn/login.jsp";
//post 开始
BBSRequest.ContentLength = replybyte.Length;
Stream newStream = BBSRequest.GetRequestStream();
newStream.Write(replybyte, 0, replybyte.Length);
newStream.Close();
//post 结束
responseHTML = GetResponseString();
string redirect = "";
redirect = SubString(responseHTML, "location.href=\"", "\"");
if (!string.IsNullOrEmpty(redirect)) {
responseHTML = LoginRedirect(redirect);
}
redirect = SubString(responseHTML, "<script type=\"text/javascript\" src=\"/online/domain.jsp?", "\"");
if (!string.IsNullOrEmpty(redirect)) {
string getCookieTianya = LoginRedirect("http://passport.tianya.cn/online/domain.jsp?"+redirect);
}
redirect = SubString(responseHTML, "location.href=\"", "\"");
//redirect = "http://www.tianya.cn/92502484";
if (!string.IsNullOrEmpty(redirect)) {
responseHTML = LoginRedirect(redirect);
}
//System.Diagnostics.Debug.Print(responseHTML);
//if (responseHTML.IndexOf("登录成功") > 0)
if (responseHTML.IndexOf("个人首页") > 0)
{
//MessageBox.Show("Login successful");
Console.WriteLine("Login successful");
}
else
{
//MessageBox.Show(responseHTML);
Console.WriteLine(responseHTML);
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
Console.WriteLine(ex.ToString());
}
}
public static string LoginRedirect(string url)
{
string responseHTML = string.Empty; ;
try
{
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
BBSRequest = (HttpWebRequest)WebRequest.Create(url);
}
else
{
BBSRequest = (HttpWebRequest)WebRequest.Create(url);
}
PrepareRequest(); BBSRequest.Method = "GET";
responseHTML = GetResponseString();
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
Console.WriteLine(ex.ToString());
}
return responseHTML;
}
public static void PrepareRequest()
{
BBSRequest.ServicePoint.Expect100Continue = false;
//是否使用 Nagle 不使用 提高效率
BBSRequest.ServicePoint.UseNagleAlgorithm = false;
//最大连接数
BBSRequest.ServicePoint.ConnectionLimit = 65500;
//数据是否缓冲 false 提高效率
BBSRequest.AllowWriteStreamBuffering = false;
BBSRequest.CookieContainer =new CookieContainer();
if (gCookieCollention.Count > 0)
{
BBSRequest.CookieContainer.Add(gCookieCollention);
}
BBSRequest.Accept = "text/html, application/xhtml+xml, */*";
BBSRequest.UserAgent = "User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko";
BBSRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
BBSRequest.Host = "passport.tianya.cn";
// BBSRequest.Expect =null;
BBSRequest.KeepAlive = true ;
BBSRequest.Credentials = CredentialCache.DefaultCredentials;
BBSRequest.AllowAutoRedirect = false;
BBSRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
public static string GetResponseString()
{
//返回HTML
BBSResponse = (HttpWebResponse)BBSRequest.GetResponse(); //gCookieCollention = BBSResponse.Cookies;
if (BBSResponse.Cookies.Count > 0) {
gCookieCollention.Add(BBSResponse.Cookies);
}
PrintCookie(); Stream dataStream = BBSResponse.GetResponseStream();
StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("utf-8"));
return reader.ReadToEnd();
}
public static bool CheckValidationResult(Object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
public static void PrintCookie()
{
foreach (Cookie cookie in gCookieCollention)
{
string cookieString = string.Format("{0}={1};Domain={2};Path={3};Secure={4};HttpOnly={5};Expires={6}",
cookie.Name,
cookie.Value,
cookie.Domain,
cookie.Path,
cookie.Secure.ToString(),
cookie.HttpOnly,
cookie.Expires.ToString());
Console.WriteLine(cookieString);
}
}
public static string SubString(string source, string start, string end)
{
if(string.IsNullOrEmpty(source)) return string.Empty;
int idxS = source.IndexOf(start, 0) + start.Length;
int idxE = source.IndexOf(end, idxS);
string ret = "";
if(idxE > idxS)
{
ret = source.Substring(idxS, (idxE - idxS));
}
return ret;
}
}
}