c#第一篇 在WPF的window窗體中使用httpwebrequest實現模擬登陸網頁,並在webbroser控件中顯示

話說我也是新手,本來是做java的,但是公司需要,所以轉到做c#,所以就邊做邊學吧。這是我做的第一個c#項目中需要用到的一些東西,希望能對初入c#的同學們有點幫助。聲明一下,有些代碼是參考別人的,或者是直接拿過來用的,這些都不再一一說明從哪來了,畢竟目的只有一個,那就是幫助自己也幫助別人學得更好!話不多說。

首先講一下要實現的功能。

在一個登陸框中,輸入登陸所需要的 賬號,密碼 。然後點擊提交按鈕,提交數據。模擬登陸網頁以後,返回登陸後網頁的數據也就是html代碼啦。接着,將html 的值賦給另外一個window窗口中的webbrowser控件並顯示。

下面說一下步驟:

第一步,建立一個輔助類Helper,輔助類可以實現以下功能:

1. 獲取網頁 cookie

2.獲取網頁的html值

代碼如下:

class Helper
    {
            /// <summary>
            /// 獲取CooKie
            /// </summary>
            /// <param name="loginUrl"></param>
            /// <param name="postdata"></param>
            /// <param name="header"></param>
            /// <returns></returns>
            public static CookieContainer GetCooKie(string loginUrl, string postdata, HttpHeader header)
            {
                HttpWebRequest request = null;
                HttpWebResponse response = null;
                try
                {
                    CookieContainer cc = new CookieContainer();
                    request = (HttpWebRequest)WebRequest.Create(loginUrl);
                    request.Method = header.method;
                    request.ContentType = header.contentType;
                    byte[] postdatabyte = Encoding.UTF8.GetBytes(postdata);
                    request.ContentLength = postdatabyte.Length;
                    request.AllowAutoRedirect = false;
                    request.CookieContainer = cc;
                    request.KeepAlive = true;


                    //提交請求
                    Stream stream;
                    stream = request.GetRequestStream();
                    stream.Write(postdatabyte, 0, postdatabyte.Length);
                    stream.Close();


                    //接收響應
                    response = (HttpWebResponse)request.GetResponse();
                    response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);


                    CookieCollection cook = response.Cookies;
                    //Cookie字符串格式
                    string strcrook = request.CookieContainer.GetCookieHeader(request.RequestUri);


                    return cc;
                }
                catch (Exception ex)
                {


                    throw ex;
                }
            }


            /// <summary>
            /// 獲取html
            /// </summary>
            /// <param name="getUrl"></param>
            /// <param name="cookieContainer"></param>
            /// <param name="header"></param>
            /// <returns></returns>
            public static string GetHtml(string getUrl, CookieContainer cookieContainer, HttpHeader header)
            {
                Thread.Sleep(1000);
                HttpWebRequest httpWebRequest = null;
                HttpWebResponse httpWebResponse = null;
                try
                {
                    httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
                    httpWebRequest.CookieContainer = cookieContainer;
                    httpWebRequest.ContentType = header.contentType;
                    httpWebRequest.ServicePoint.ConnectionLimit = header.maxTry;
                    httpWebRequest.Referer = getUrl;
                    httpWebRequest.Accept = header.accept;
                    httpWebRequest.UserAgent = header.userAgent;
                    httpWebRequest.Method = "GET";
                    httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    Stream responseStream = httpWebResponse.GetResponseStream();
                    StreamReader streamReader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("GBK"));
                    string html = streamReader.ReadToEnd();
                    streamReader.Close();
                    responseStream.Close();
                    httpWebRequest.Abort();
                    httpWebResponse.Close();
                    return html;
                }
                catch (Exception e)
                {
                    if (httpWebRequest != null) httpWebRequest.Abort();
                    if (httpWebResponse != null) httpWebResponse.Close();
                    return string.Empty;
                }
            }
        } <span style="font-family: Arial, Helvetica, sans-serif;">//這個是用來設置/獲取頭信息</span>
<span style="font-family: Arial, Helvetica, sans-serif;">  public class HttpHeader</span>
    {
        public string contentType { get; set; }


        public string accept { get; set; }


        public string userAgent { get; set; }


        public string method { get; set; }


        public int maxTry { get; set; }
    }


}
以上就是輔助類 
輔助類完了以後 就需要在 mainwindow.xmal.cs添加代碼了。
添加 提交按鈕點擊事件。。。自動生成,寫一下代碼就差不多了。
 private void btnSumbit_Click(object sender, RoutedEventArgs e)
        {


            string name = this.txbName.Text;   //獲取窗口中 textbox 的值
            string pasword = this.passWord.Password; // 獲取密碼輸入框的值
            HttpHeader header = new HttpHeader();
            header.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
            header.contentType = "application/x-www-form-urlencoded";
            header.method = "POST";
            header.userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
            header.maxTry = 300;
 //以上信息基本上是固定的。。理解即可
            string html = Helper.GetHtml("XXX.sjp", Helper.GetCooKie("XXXjsp",  //第一個地址是需要返回的地址,第二個地址就是你需要登錄的地址 
                  "connDN=&officeType=&username=XXX&password=XXX", header), header); //這是網頁中需要傳遞的參數  具體需要什麼也是根據網頁來定 可以同時使用                                                                                    //fiddler軟件來查看。
            Window1 w = new Window1(); //新建一個window實例
           
            w.WebBrowserHtml.NavigateToString(html);  //返回的html在webbroser中顯示。




           // w.Html = html;
            w.Show();}

以上就是主要代碼。至於那些window 代碼,xaml代碼 這裏就不再寫出來。直接添加即可。沒什麼技術含量。

我覺得到了這一步,基本上算是完事兒。

最主要的及時把邏輯給弄清楚。

獲取cookie ,獲取htnl,然後再顯示出來。 方法都已經 列好,很容易理解。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章