C#Persistent WebClient

时间:2010-12-22 15:21:04

标签: .net webclient

我有一个用C#编写的类(Windows窗体)

这是一个WebClient类,我打算在某些网站中使用,以及登录和导航。

这是完整的课程pastebin.com(该课程有197行,所以我只使用了pastebin。抱歉,如果我让你有点难以阅读课程,也请在这篇文章下面)

问题是,我不确定为什么它不会持久...我能够登录,但当我导航到其他页面(不离开域名)时,我被扔回登录页面。

你能帮我解决这个问题吗?

但是,有一个问题是,我尝试连接的网站是“HTTPS”协议。我还没有在常规HTTP上测试过这个。

提前谢谢。

/*
 * Web Client v1.2
 * ---------------
 * Date: 12/17/2010
 * author: Jayson Ragasa
 */

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Web;

namespace Nullstring.Modules.WebClient
{
    public class WebClientLibrary
    {
        #region vars

        string _method = string.Empty;

        ArrayList _params;
        CookieContainer cookieko;
        HttpWebRequest req = null;
        HttpWebResponse resp = null;
        Uri uri = null;

        #endregion

        #region properties
        public string Method
        {
            set { _method = value; }
        }
        #endregion

        #region constructor
        public WebClientLibrary()
        {
            _method = "GET";
            _params = new ArrayList();
            cookieko = new CookieContainer();
        }
        #endregion

        #region methods
        public void ClearParameter()
        {
            _params.Clear();
        }

        public void AddParameter(string key, string value)
        {
            _params.Add(string.Format("{0}={1}", WebTools.URLEncodeString(key), WebTools.URLEncodeString(value)));
        }

        public string GetResponse(string URL)
        {
            StringBuilder response = new StringBuilder();

            #region create web request
            {
                uri = new Uri(URL);
                req = (HttpWebRequest)WebRequest.Create(URL);
                req.Method = "GET";
                req.GetLifetimeService();
            }
            #endregion

            #region get web response
            {
                resp = (HttpWebResponse)req.GetResponse();
                Stream resStream = resp.GetResponseStream();

                int bytesReceived = 0;
                string tempString = null;
                int count = 0;
                byte[] buf = new byte[8192];

                do
                {
                    count = resStream.Read(buf, 0, buf.Length);

                    if (count != 0)
                    {
                        bytesReceived += count;
                        tempString = Encoding.UTF8.GetString(buf, 0, count);
                        response.Append(tempString);
                    }
                }
                while (count > 0);
            }
            #endregion

            return response.ToString();
        }

        public string GetResponse(string URL, bool HasParams)
        {
            StringBuilder response = new StringBuilder();

            #region create web request
            {
                uri = new Uri(URL);

                req = (HttpWebRequest)WebRequest.Create(URL);
                req.MaximumAutomaticRedirections = 20;
                req.AllowAutoRedirect = true;

                req.Method = this._method;
                req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                req.KeepAlive = true;

                req.CookieContainer = this.cookieko;
                req.UserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10";
            }
            #endregion

            #region build post data
            {
                if (HasParams)
                {
                    if (this._method.ToUpper() == "POST")
                    {
                        string Parameters = String.Join("&", (String[])this._params.ToArray(typeof(string)));

                        UTF8Encoding encoding = new UTF8Encoding();
                        byte[] loginDataBytes = encoding.GetBytes(Parameters);

                        req.ContentType = "application/x-www-form-urlencoded";
                        req.ContentLength = loginDataBytes.Length;

                        Stream stream = req.GetRequestStream();
                        stream.Write(loginDataBytes, 0, loginDataBytes.Length);
                        stream.Close();
                    }
                }
            }
            #endregion

            #region get web response
            {
                resp = (HttpWebResponse)req.GetResponse();
                Stream resStream = resp.GetResponseStream();

                int bytesReceived = 0;
                string tempString = null;
                int count = 0;
                byte[] buf = new byte[8192];

                do
                {
                    count = resStream.Read(buf, 0, buf.Length);

                    if (count != 0)
                    {
                        bytesReceived += count;
                        tempString = Encoding.UTF8.GetString(buf, 0, count);
                        response.Append(tempString);
                    }
                }
                while (count > 0);
            }
            #endregion

            return response.ToString();
        }
        #endregion
    }

    public class WebTools
    {
        public static string EncodeString(string str)
        {
            return HttpUtility.HtmlEncode(str);
        }

        public static string DecodeString(string str)
        {
            return HttpUtility.HtmlDecode(str);
        }

        public static string URLEncodeString(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        public static string URLDecodeString(string str)
        {
            return HttpUtility.UrlDecode(str);
        }
    }
}

更新12月22日
GetResponse超载

public string GetResponse(string URL)
{
    StringBuilder response = new StringBuilder();

    #region create web request
    {
        //uri = new Uri(URL);
        req = (HttpWebRequest)WebRequest.Create(URL);
        req.Method = "GET";
        req.CookieContainer = this.cookieko;
    }
    #endregion

    #region get web response
    {
        resp = (HttpWebResponse)req.GetResponse();
        Stream resStream = resp.GetResponseStream();

        int bytesReceived = 0;
        string tempString = null;
        int count = 0;
        byte[] buf = new byte[8192];

        do
        {
            count = resStream.Read(buf, 0, buf.Length);

            if (count != 0)
            {
                bytesReceived += count;
                tempString = Encoding.UTF8.GetString(buf, 0, count);
                response.Append(tempString);
            }
        }
        while (count > 0);
    }
    #endregion

    return response.ToString();
}

但我仍然被扔回登录页面。

更新日期:12月23日
我尝试列出cookie,这就是我得到的内容

首先,我必须登录到webform,这个我有这个Cookie JSESSIONID = 368C0AC47305282CBCE7A566567D2942

然后我导航到另一个页面(但在同一个域上)我有一个不同的库克? JSESSIONID = 9FA2D64DA7669155B9120790B40A592C

出了什么问题?我使用去年12月22日更新的代码

2 个答案:

答案 0 :(得分:1)

您需要在第一个GetResponse重载中使用CookieContainer。

答案 1 :(得分:1)

如果使用GetResponse(字符串URL)覆盖导航到第二页,则它不会将cookie容器附加到请求,因此不会传递登录请求中的会话cookie(通常包含auth令牌)到服务器。因此,服务器不知道您已经登录。

更改您的代码以将cookie容器附加到所有请求,它应该可以正常工作。

或者,查看Web服务器是否接受来自无cookie客户端的登录(通过在URL参数中发送会话信息)并更改您的代码以使用该方法。