Code Bye

关于c#模拟登录 响应无法获取cookie值

原因是有个值是在响应头中set-cookie中取来的  但是本人写的代码,响应中cooikes的个数为0 这哪里错了 大家帮帮忙
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace asd
{
    class Program
    {
        public static CookieCollection GetCooKie(string loginUrl)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(loginUrl);
                request.Method = "GET";
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)";
                request.Accept = "text/html, application/xhtml+xml, */*";
                response = (HttpWebResponse)request.GetResponse();
                return response.Cookies;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        static void Main(string[] args)
        {
            CookieCollection c = GetCooKie("http://www.zjhpyy.com/login.jhtml");
            for (int i = 0; i < c.Count;i++ )
            {
                Cookie cc = c[i];
            }
        }
    }
}
解决方案

40

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var request = (HttpWebRequest)WebRequest.Create("http://www.baidu.com");
            request.CookieContainer = new CookieContainer();        //注意这句
            request.Method = "GET";
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)";
            request.Accept = "text/html, application/xhtml+xml, */*";
            var response = (HttpWebResponse)request.GetResponse();
            foreach (Cookie cookie in response.Cookies)
            {
                Console.WriteLine("{0}: {1}", cookie.Name, cookie.Value);
            }
            Console.ReadLine();
        }
    }
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于c#模拟登录 响应无法获取cookie值