我想写一个自动登录产看信息的程序
抓包分析,只要用浏览器访问
http://xxxx.xxx/loginChk.asp?Passwd=111&user=111
就可以登录,然后在当前浏览器页面跳转到
http://xxxx.xxx/info.asp
就可以查看个人信息。但是在编程时,发现使用WebClient类等,每次发起的访问,session值都不一样。而服务器应该是靠session验证的。
我想知道WebClient或者其他访问http的类,如何实现保留当前session的跳转。
c#刚入门 ,希望给段代码 private void button1_Click(object sender, EventArgs e)
        {  
WebClient wc = new WebClient();
            
           Stream st  = wc.OpenRead("http://xxxx.xxx/loginChk.asp?Passwd=111&user=111");
           StreamReader sr = new StreamReader(st);
           string res = sr.ReadToEnd();
           richTextBox1.AppendText(res);
           //这里就是无法实现保留当前session的跳转,所以错误。
           Stream st1 = wc.OpenRead("http://xxxx.xxx/info.asp");
           StreamReader sr1 = new StreamReader(st1);
           string res1 = sr1.ReadToEnd();
           richTextBox1.AppendText(res1);        }

解决方案 »

  1.   

    WebClient.Credentials 属性:获取或设置发送到主机并用于对请求进行身份验证的网络凭据。
    Credentials 属性包含的身份验证凭据用于访问主机上的资源。在多数客户端方案中,应使用 DefaultCredentials,这是当前登录的用户的凭据。为此,将 UseDefaultCredentials 属性设置为 true,而不是设置此属性。如果 WebClient 类用于中间层应用程序(如 ASP.NET 应用程序),则 DefaultCredentials 属于运行 ASP 页的帐户(服务器端凭据)。通常,将此属性设置为名义上发出请求的客户端的凭据。
    尝试用这个试试。
      

  2.   

    自己找到答案了
    重写一下WebClient类using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;namespace demo
    {
        public class HttpClient : WebClient
        {
            private CookieContainer cookieContainer;
            public HttpClient()
            {
                //
                // TODO: 在此处添加构造函数逻辑
                //
                this.cookieContainer = new CookieContainer();        }
            /**/
            /// <summary>
            /// 创建一个新的 WebClient 实例。
            /// </summary>
            /// <param name="cookie">Cookie 容器</param>
            public HttpClient(CookieContainer cookies)
            {
                this.cookieContainer = cookies;
            }        /**/
            /// <summary>
            /// Cookie 容器
            /// </summary>
            public CookieContainer Cookies
            {
                get { return this.cookieContainer; }
                set { this.cookieContainer = value; }
            }        /**/
            /// <summary>
            /// 返回带有 Cookie 的 HttpWebRequest。
            /// </summary>
            /// <param name="address"></param>
            /// <returns></returns>
            protected override WebRequest GetWebRequest(Uri address)
            {
                WebRequest request = base.GetWebRequest(address);
                if (request is HttpWebRequest)
                {
                    HttpWebRequest httpRequest = request as HttpWebRequest;
                    httpRequest.CookieContainer = cookieContainer;
                }
                return request;
            }    }
    }