您的位置:首页 > 理论基础 > 计算机网络

c#第一篇 在WPF的window窗体中使用httpwebrequest实现模拟登陆网页,并在webbroser控件中显示

2014-06-27 16:59 1106 查看
话说我也是新手,本来是做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,然后再显示出来。 方法都已经 列好,很容易理解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: