解决方案 »

  1.   

    抓包试试 cookies 值有没有返回给你
      

  2.   

    using System;
    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;
                }
            }
        }
    }
      

  3.   

    你的代码里面有BBSRequest.CookieContainer =new  CookieContainer();,这样的话每次CookieContainer都是空的。你在发送请求之前也没有往里面添加任何Cookie。
    另外你下面的代码不知道是做什么用的。既然你前面的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)看一下
      

  4.   

    你虽然设置了cookieJar,但是每次请求后你并没有把httpRes.Cookies添加进去,你是不是觉得Cookies自己会添加进去?请求完后输出一下看看结果是否cookieJar是否有变化。
      

  5.   

    这是第一次请求,就是初始的,第一次POST请求,   if (BBSResponse.Cookies.Count == 0)这句就是判断有没有Cookies的,等于0就是没有,BBSResponse.Cookies=   BBSRequest.CookieContainer.GetCookies(BBSResponse.ResponseUri);这句就是再看看有没有,真的没有了的话,GetUriCookieContainer(BBSResponse.ResponseUri).GetCookies(BBSResponse.ResponseUri);就从IE里取,但是从IE里取的话必须是用户使用IE打开了才能取到,不然取不到,其实这样做没有意义,我这的目的是想POST后,取到Cookies,从IE取没有用,不过这里也多余了一下,因为只是调试,然后 gCookieCollention = BBSResponse.Cookies;这里是POST后取到的Cookies保存到全局变量,以便其它的请求使用这些Cookies,这是第一次POST,所以在这里做了赋值,像这BBSRequest.CookieContainer.Add(gCookieCollention)这样的用法就是其它POST的时候要使用到我第一次POST时的Cookies时才添加,这里是第一次所以就没有添加,就是要添加,第一次时,gCookieCollention也是没有的
      

  6.   

    你真的调试了吗?我用你的代码去调试,Cookies.Count===0是0啊,是0就是没有啊
      

  7.   


    这是抓包的图,是不是没有Cookies返回呢,那要怎么做才有呀,通过谷歌浏览器登录查询都有的,为什么直接POST就没有呢,有没有办法让他有呢?
      

  8.   

    破图了. Fiddler.exe 试试. 你在网页上面走你流程和你用程序走流程看那个地方的cookies值不一样.相对就容易解决了. 
    在非https 的情况下(很少用过). request.中的cookies值基本上都能拿到的. 没有天涯帐号.就不方便测试了. 
      

  9.   

    他返回的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 中拿
      

  10.   

    天涯登陆的时候,是分了好几步的。
    第一步,登陆后,在返回页面里面通过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;
    }
    }
    }