能够接受cookie的Http客户端

时间:2011-11-09 22:35:40

标签: c# cookies httpclient

我尝试通过执行带有必需参数的POST来访问ba.com(实际网址:“https://www.britishairways.com/travel/loginr/public/en_us?eId=109001”),它会回复3XX重定向,该重定向指向具有{{1}的网址https://www.britishairways.com/cookie.html我尝试使用带Set-Cookie的请求标头Cookie进行GET,此时,它返回2XX表示cookie未启用。

对于gmail.com,当我使用必需参数执行POST时,它会直接返回带有key=value;key=value ...标头的2XX响应,并声明该cookie未启用。

我的问题是:

  1. 通常,客户端和服务器之间的HTTP(S)序列是什么,用于验证cookie是否已启用?
  2. 我的一般目的是通过程序访问我的帐户,登录并查看有关我帐户的一些信息。 britshairways.com/gmail.com可能是一个好的开始。 (这类似于模拟的网络浏览器)
  3. 如果有人知道可以完成任务的示例代码,我想学习。感谢。

    以下非工作样本代码,详细参数请致电britishairways.com/gmail.com

    Set-Cookie

    致电ba.com(格式:uri,key,value pairs):

    public static void PostToUrlWithCookies(string uri, NameValueCollection nvc, CookieCollection cookies, string cookieHeader = "")
    {
        // this is what we are sending
        string post_data = "";
        if (nvc != null)
        {
            foreach (string key in nvc.Keys)
            {
                string formitem = string.Format("{0}={1}", key, nvc[key]);
                if (post_data == "")
                {
                    post_data += formitem;
                }
                else
                {
                    post_data += "&" + formitem;
    
                }
            }
        }
        Console.WriteLine("post_data={0}", post_data);
    
    
        // create a request
        HttpWebRequest request = (HttpWebRequest)
        WebRequest.Create(uri);
    
        // to accept cookies (and skip 100 response)
        //var cookies = new CookieContainer(); 
        ServicePointManager.Expect100Continue = false;
    
        string newCookieHeader = "";
        request.CookieContainer = new CookieContainer();
        if (cookies.Count > 0)
        {
            CookieCollection oCookies = cookies;
    
            for (int j = 0; j < oCookies.Count; j++)
            {
                Cookie oCookie = oCookies[j];
                Cookie oC = new Cookie();
    
                // Convert between the System.Net.Cookie to a System.Web.HttpCookie...
                oC.Domain = request.RequestUri.Host;
                oC.Expires = oCookie.Expires;
                oC.Name = oCookie.Name;
                oC.Path = oCookie.Path;
                oC.Secure = oCookie.Secure;
                oC.Value = oCookie.Value;
    
                if (newCookieHeader != "")
                {
                    newCookieHeader += ";";
                }
                newCookieHeader += oC.Name + "=" + oC.Value;
    
                //request.CookieContainer.Add( oC );
            }
    
        }
    
    
        //      Console.WriteLine("request has {0} cookies inside", request.CookieContainer.Count);
    
        if (cookieHeader != "")
        {
            request.Headers["Cookie"] = newCookieHeader;
            Console.WriteLine("request Set-Cookie: {0}", newCookieHeader);
        }
    
    
        // add a fake cookie to request
        //Cookie aCookie = new Cookie("lastVisited", DateTime.Now.ToString());
        //aCookie.Domain = "ba.com";
        //request.CookieContainer.Add(aCookie);
    
        request.KeepAlive = true;
        request.ProtocolVersion = HttpVersion.Version11;
        if (cookies.Count == 0)
        {
            request.AllowAutoRedirect = false;   // ba.com testing cookies using a 3XX Redirect
            request.Method = "POST";
        }
        else
        {
            request.AllowAutoRedirect = false;
            request.Method = "GET";
        }
        //    
        // turn our request string into a byte stream
        byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
    
        // this is important - make sure you specify type this way
        if (request.Method == "POST")
        {
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2";
            request.ContentLength = postBytes.Length;
            Stream requestStream = request.GetRequestStream();
            //      
            //      // now send it
            if (post_data != "")
            {
                requestStream.Write(postBytes, 0, postBytes.Length);
            }
            requestStream.Close();
        }
        else
        {
            request.UserAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2";
        }
    
        //       
        // grab te response and print it out to the console along with the status code
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        foreach (Cookie cook in response.Cookies)
        {
            //               Console.WriteLine("Cookie:");
            //              Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
            cookies.Add(cook);
        }
    
        cookieHeader = response.GetResponseHeader("Set-Cookie");
        Console.WriteLine("responce-> Set-Cookie: {0}", cookieHeader);
    
    
        for (int i = 0; i < response.Headers.Count; ++i)
            Console.WriteLine("\nHeader Name:{0}, Value :{1}", response.Headers.Keys[i], response.Headers[i]);
    
    
        if ((int)response.StatusCode >= 300 && (int)response.StatusCode < 400)
        {
            string cookieUrl = response.Headers["Location"];
            Console.WriteLine("about to verify cookie via url {0}", cookieUrl);
    
    
    
    
            // verify the cookie capability
            PostToUrlWithCookies(cookieUrl, null /*nvc*/, cookies, cookieHeader);
        }
        else
        {
            Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
            Console.WriteLine((int)response.StatusCode);
    
        }
    
    
    }
    

    致电gmail.com

    func "https://www.britishairways.com/travel/loginr/public/en_us?eId=109001","loginText", "Login+ID", "Directional_Login", "%2Ftravel%2Fechome%2Fexecclub%2Fen_us%3FmembershipNumber%3D36436959%26DM1%255FmktgCat%3DEmail%26DM1%255FMktgSubCat%3D2%26DM1%255Fcampaign%3DBBBB5YT0BPKCBBBB5YT0BQBG%26DM1%255FChksm%3D117285700%26DM1_SRC%3D%26utm_source%3DeD%26utm_medium%3DEmail%26utm_campaign%3DEmail%26utm_term%3DBBBB5YT0BQBG%26utm_content%3DBBBB5YT0BPKC", "membershipNumber", "XXXXXX", "password", "XXXXXX", "passwordtext", "XXXXXXX" 
    

1 个答案:

答案 0 :(得分:1)

向WebRequest添加cookie支持只需几行代码。

var cookies = new CookieContainer();

// perform normal request;
var webResponse; // be sure this gets assigned

cookies.Add(webResponse.Cookies);

// create another request
var webRequest; // be sure this gets assigned

webRequest.CookiesContainer = cookies;

// perform next request. This time with cookies.