欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WinForm项目开发中WebBrowser用法实例汇总

程序员文章站 2023-12-18 11:27:58
本文实例汇总了winform项目开发中webbrowser用法,希望对大家项目开发中使用webbrowser起到一定的帮助,具体用法如下: 1. [permis...

本文实例汇总了winform项目开发中webbrowser用法,希望对大家项目开发中使用webbrowser起到一定的帮助,具体用法如下:

1.

[permissionset(securityaction.demand, name = "fulltrust")]
[comvisibleattribute(true)]
public partial class frmwebdata : form
{
public frmwebdata()
{
  initializecomponent();
}
protected override void onload(eventargs e)
{
  wbservice.objectforscripting = this;
  base.onload(e);
}
}

2.后台调用javascript脚本

<script type="text/javascript" language="javascript">
function errormessage(message) {
  document.getelementbyid("error").innertext = message;
}
</script>
后台代码

static string errormsg = string.empty;
private void wbservice_documentcompleted(object sender, webbrowserdocumentcompletedeventargs e)
{
  if (!string.isnullorempty(errormsg))
 wbservice.document.invokescript("errormessage", new object[1] { string.format("操作失败,原因:{0}!", errormsg) });
}

3.javascript脚本调用后台方法

脚本代码

  <div id="content">
 <h2 id="error">
   操作正在响应中.....</h2>
 <div class="utilities">
   <a class="button right" 
onclick="window.external.dosvrwebdbback()">

刷新

</a> 
   <!--<a class="button right"
 onclick="window.external.navigatetologin()">重新登录</a>-->
   <div class="clear">
   </div>
 </div>
  </div>

后台代码

public void dosvrwebdbback()
{
  try
  {
  }
  catch (timeoutexception)
  {
 errormsg = "超时,请稍候再尝试!";
  }
  catch (exception ex)
  {
 errormsg = ex.message.tostring();
  }
}

4.设置cookie

cookie _cookie = basewinform.loginmessage.sessionid2;
   internetsetcookie(basewinform.loginmessage.svrwebdbback, "asp.net_sessionid", _cookie.value);
   wbservice.navigate(basewinform.loginmessage.svrwebdbback, null, null, string.format("referer:{0}", basewinform.loginmessage.svrwebdbloingurl));
[dllimport("wininet.dll", charset = charset.auto, setlasterror = true)]
public static extern bool internetsetcookie(string urlname, string cookiename, string cookiedata);

5.请求链接获取返回处理

public class httpwebrequesttoolv2
{
public delegate httpwebrequest requestrule(string url);
/// <summary>
/// 发起httpwebresponse请求
/// </summary>
/// <param name="url">请求连接</param>
/// <param name="credentials">请求参数</param>
/// <param name="httpwebrequestrule">请求设置『委托』,当委托等于null的时候,默认请求;否则使用所设置的httpwebrequest</param>
/// <returns>httpwebresponse</returns>
public static httpwebresponse createhttpwebrequest(string url, byte[] credentials, requestrule httpwebrequestrule)
{
  if (string.isnullorempty(url))
 throw new argumentnullexception("url");

  httpwebrequest _request = null;
  if (httpwebrequestrule != null)
  {
 _request = httpwebrequestrule(url);
  }
  else
  {
 _request = webrequest.create(url) as httpwebrequest;
 _request.method = "post";
 _request.contenttype = "application/x-www-form-urlencoded";
 _request.cookiecontainer = new cookiecontainer();
  }

  if (credentials != null)
  {
 _request.contentlength = credentials.length;
 using (var requeststream = _request.getrequeststream())
 {
   requeststream.write(credentials, 0, credentials.length);
 }
  }
  return _request.getresponse() as httpwebresponse;
}

/// <summary>
/// 创建验证凭证
/// eg:
/// idictionary<string, string> _requestcredentials = new dictionary<string, string>();
///_requestcredentials.add("username", _username);
///_requestcredentials.add("password", _userpwd);
///_requestcredentials.add("macaddress", _macaddress);
///byte[] _credentials = httpwebrequesttoolv2.createcredentials(_requestcredentials, encoding.utf8);
/// </summary>
/// <returns></returns>
public static byte[] createcredentials(idictionary<string, string> credentials, encoding encoding)
{
  if (credentials == null)
 throw new argumentnullexception("credentials");
  if (credentials.count == 0)
 throw new argumentexception("credentials");
  if (encoding == null)
 throw new argumentnullexception("encoding");

  stringbuilder _credentials = new stringbuilder();
  foreach (keyvaluepair<string, string> credential in credentials)
  {
 _credentials.appendformat("{0}={1}&", credential.key, credential.value);
  }
  string _credentialsstring = _credentials.tostring().trim();
  int _endindex = _credentialsstring.lastindexof('&');
  if (_endindex != -1)
 _credentialsstring = _credentialsstring.substring(0, _endindex);
  return encoding.getbytes(_credentialsstring);

}

使用示例

public static httpwebrequest requestsetting(string url)
{
  httpwebrequest _request = null;
  _request = webrequest.create(url) as httpwebrequest;
  _request.method = "post";
  _request.contenttype = "application/x-www-form-urlencoded";
  _request.timeout = 1000 * 10;//超时五秒
  _request.cookiecontainer = new cookiecontainer();
  return _request;
}

/// <summary>
/// 登录web网页验证
/// </summary>
/// <param name="url">超链接</param>
/// <param name="_username">用户名</param>
/// <param name="_userpwd">密码</param>
/// <param name="_macaddress">mac地址</param>
/// <param name="sessionid">会话</param>
/// <returns>网页登录验证是否成功『失败,将抛出网页验证验证失败信息』</returns>
public bool processremotelogin(string url, string _username, string _userpwd, string _macaddress, out cookie sessionid)
{

  bool _checkresult = false;
  string _errormessage = string.empty;
  //--------------------创建登录凭证--------------------
  idictionary<string, string> _requestcredentials = new dictionary<string, string>();
  _requestcredentials.add("username", _username);
  _requestcredentials.add("password", _userpwd);
  _requestcredentials.add("macaddress", _macaddress);

  byte[] _credentials = httpwebrequesttoolv2.
createcredentials

(_requestcredentials, encoding.utf8);
  //-----------------------------------------------------

  cookiecollection _cookie = null;
  /*
   *logintype 1:成功 0:失败 
   *err 失败原因
   */
  using (httpwebresponse _httprespone = httpwebrequesttoolv2.
createhttpwebrequest

(url, _credentials, requestsetting))
  {
 _cookie = new cookiecollection();
 if (_httprespone.cookies.count > 0)
   _cookie.add(_httprespone.cookies);
  }
  //-------------------------------------------------------
  cookie _logintype = _cookie["logintype"];
  sessionid = _cookie["asp.net_sessionid"];
  cookie _err = _cookie["err"];
  if (_logintype != null && _err != null && sessionid != null)
  {
 _checkresult = _logintype.value.equals("1");
 if (!_checkresult)
   _errormessage = httputility.urldecode(_err.value);
  }
  else
  {
 _errormessage = "web服务异常,请稍候在试!";
  }
  if (!string.isnullorempty(_errormessage))
 throw new exception(_errormessage);
  return _checkresult;
}

6.从webbrowser中获取cookiecontainer

/// <summary>
/// 从webbrowser中获取cookiecontainer
/// </summary>
/// <param name="webbrowser">webbrowser对象</param>
/// <returns>cookiecontainer</returns>
public static cookiecontainer getcookiecontainer(this webbrowser webbrowser)
{
  if (webbrowser == null)
 throw new argumentnullexception("webbrowser");
  cookiecontainer _cookiecontainer = new cookiecontainer();

  string _cookiestring = webbrowser.document.cookie;
  if (string.isnullorempty(_cookiestring)) return _cookiecontainer;

  string[] _cookies = _cookiestring.split(';');
  if (_cookies == null) return _cookiecontainer;

  foreach (string cookiestring in _cookies)
  {
 string[] _cookienamevalue = cookiestring.split('=');
 if (_cookienamevalue.length != 2) continue;
 cookie _cookie = new cookie(_cookienamevalue[0].trim().tostring(), _cookienamevalue[1].trim().tostring());
 _cookiecontainer.add(_cookie);
  }
  return _cookiecontainer;
}

上一篇:

下一篇: