1) 方案一,  使用Web Service  基础功能没问题, 只是在连接https (ssh) 网站时, 需要针对https进行开发 (即http 和https 生成两套接口, 不太容易统一 ).   后来改为使用web页面交互(实质是.ashx) 结果也遇到了不少问题.

 
2) 方案二, 使用 HttpWebRequest .    HttpWebRequest 这东西get数据很容易, POST却很麻烦, 最终代码如下:
 
 public class WebApiClient
{
public string Url { get; set; }
private CookieContainer Cookies = new CookieContainer(); public static string Get( string url )
{
//this code can fix https after .net 4.6
if (url.StartsWith("https", StringComparison.CurrentCultureIgnoreCase))
{
System.Net.ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
}
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded"; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s = response.GetResponseStream();
using (StreamReader reader = new StreamReader(s))
{
string strValue = reader.ReadToEnd();
return strValue;
}
}
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
public Result<DataTable> CallWebApi(string action, string json )
{
return CallWebApi(action, json, null, null);
}
public Result<DataTable> CallWebApi(string action, string json, string fileName, byte[] fileData)
{
string responseContent;
var memStream = new MemoryStream();
var webRequest = (HttpWebRequest)WebRequest.Create(Url);
var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
//var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
webRequest.Method = "POST";
//webRequest.Timeout = timeOut;
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
if (!string.IsNullOrEmpty(fileName))
{
const string filePartHeader =
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
"Content-Type: application/octet-stream\r\n\r\n";
var header = string.Format(filePartHeader, "file1", fileName);
var headerbytes = Encoding.UTF8.GetBytes(header);
memStream.Write(beginBoundary, , beginBoundary.Length);
memStream.Write(headerbytes, , headerbytes.Length);
memStream.Write(fileData, , fileData.Length);
} var stringKeyHeader = "\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"" +
"\r\n\r\n{1}\r\n";
var bytes = Encoding.UTF8.GetBytes(string.Format(stringKeyHeader, "action", action));
memStream.Write(bytes, , bytes.Length);
bytes = Encoding.UTF8.GetBytes(string.Format(stringKeyHeader, "json", json));
memStream.Write(bytes, , bytes.Length); memStream.Write(endBoundary, , endBoundary.Length);
webRequest.ContentLength = memStream.Length;
var requestStream = webRequest.GetRequestStream();
memStream.Position = ;
var tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, , tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, , tempBuffer.Length);
requestStream.Close();
var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
Encoding.GetEncoding("utf-8")))
{
responseContent = httpStreamReader.ReadToEnd();
}
httpWebResponse.Close();
webRequest.Abort();
try
{
return JsonConvert.DeserializeObject<Result<DataTable>>(responseContent);
}
catch (Exception ex)
{
throw new ApplicationException("Parse server result error: " + responseContent, ex);
}
} }
POST数据的麻烦, 封装一下可以忍了, 但是连接HTTPS的网站时, 有的网站可以, 有的网站会出错:System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
   at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.ConnectStream.WriteHeaders(Boolean async)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.GetResponse()
 
如果是普通的桌面程序 , 在.net 4.6以上版本时, Create HttpWebRequest 对象前添加
  1. if(url.StartsWith("https",StringComparison.CurrentCultureIgnoreCase))
  2. {
  3. System.Net.ServicePointManager.ServerCertificateValidationCallback=newRemoteCertificateValidationCallback(CheckValidationResult);
  4. }
  1. privatestatic bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain,SslPolicyErrors errors)
  2. {
  3. returntrue;
  4. }
 
有的web服务器要求较新的HTTPS的安装协议, 这种情况下.net4.0以下的版本不支持, 因此要升级到.net4.6以上, 并且在创建HttpWebRequest对象前加入如下设置代码:
  1. ServicePointManager.SecurityProtocol=SecurityProtocolType.Tls|SecurityProtocolType.Tls11|SecurityProtocolType.Tls12|SecurityProtocolType.Ssl3;
这样就可以最大程度的兼容各种安全协议了. 有的时候发现我们的程序挑.net framework的版本, 大都是由这个原因引起的.
解决了HttpWebRequest连接HTTPS的问题之后, 该方案成为了功能最强的方案(重要是能较好的支持文件的上传)
 
方案三 使用WebBrowser控件 .
 
初步试了一下, get https的页面没有问题, post 的略有麻烦, 网上查到的方法是截获post事件进行处理:

WebBrowser 其实是对 ActiveX 控件 SHDocVw 的封装,而这个SHDocVw的很多底层调用WebBrowser控件并没有提供实现,我们需要直接操作 SHDoceVw 控件来实现这些高级调用。操作方法如下:
1、在 windows/system32 目录下找到 shdocvw.dll 这个动态库,将其添加到引用中

2、在 Form1_Load 中添加如下语句

SHDocVw.WebBrowser wb = (SHDocVw.WebBrowser)webBrowser1.ActiveXInstance; 
wb.BeforeNavigate2 += new DWebBrowserEvents2_BeforeNavigate2EventHandler(WebBrowser_BeforeNavigate2);

3、添加如下成员函数

private void WebBrowser_BeforeNavigate2(object pDisp, ref object URL, ref object Flags, 
ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)
{
string postDataText = System.Text.Encoding.ASCII.GetString(PostData as byte[]);
}

完成上述3步后,你post 数据时, 就会响应 BeforeNavigate2 事件,postDataText 中就是你post的数据。你也可以修改PostData,对这些数据进行转换或加密。

感觉会比较麻烦, 其实还有一种方法,就是利用WebBrowser的DocumentText属性注入脚本(执行脚本), 然后利用Ajax的方式和web服务器进行交互. 之后利用JS和C#互操作来完成相应的功能.

互操作的C#类上需要加上这个设置:
  1. [System.Runtime.InteropServices.ComVisibleAttribute(true)]
并且运行此代码:
  1. webBrowser1.ObjectForScripting=this;
C#里调用JS方法:
  1. webBrowser1.Document.InvokeScript("jsFunction",newstring[]{‘ssss’});
 
JS里调用C#方法:
  1. window.external.CSharpFunction(‘呵呵’);
这个方法也有些麻烦的地方, 而且不支持文件的上传.

记Outlook插件与Web页面交互的各种坑 (含c# HttpWebRequest 连接https 的完美解决方法)的更多相关文章

  1. (基础篇)PHP与Web页面交互

    PHP与Web页面交互是实现PHP网站与用户交互的重要手段.在PHP中提供了两种与Web页面交互的方法,一种是通过Web表单提交数据,另一种是通过URL参数传递. 这里我们将详细讲解表单的相关知识,为 ...

  2. PHP与web 页面交互

    PHP与Web页面交互是实现PHP网站与用户交互的重要手段.在PHP中提供了两种与Web页面交互的方法,一种是通过Web表单提交数据,另一种是通过URL参数传递. 这里我们将详细讲解表单的相关知识,为 ...

  3. 5.PHP与Web页面交互

    PHP与Web页面交互 PHP中提供了两种与Web页面交互的方法,一种是通过Web表单提交数据,另一种是通过URL参数传递. 表单提交用户名字和密码: <form name "form ...

  4. Chrome插件触发web页面的事件

    Chrome插件中不能直接调用Web页面的元素js,原因是chrome插件的机制http://stackoverflow.com/questions/17819344/triggering-a-cli ...

  5. php与web页面交互(二)

    一.获取表单数据 1.1 使用POST()方法提交表单  ---POST()方法可以没有限制地传递数据到服务器,所提交的数据在后台传输,用户在浏览器端是看不到这一过程的,安全性高,适用于发送保密数据和 ...

  6. php与web页面交互

    一.web表单 web表单的功能是让浏览者和网站有一个互动的平台.web表单主要用来在网页中发送数据到服务器. 1.1 表单的创建 使用form标记,并在其中插入相关的表单元素,即可创建一个表单. & ...

  7. web页面动态加载UserControl,并调用用户控件中的方法来初始化控件

    1,HTML页 头部注册: <%@ Register Src="~/WorkLog/WorkLogNewV1/UserControl/CeShiBu.ascx" TagPre ...

  8. JAVA and JAVA WEB with TOMCAT and ECLIPSE 学习过程中遇到的字符乱码问题及解决方法汇总(随时补充)

    JAVA语言具有跨平台,unicode字符集编码的特点. 但是在开发过程中处理数据时涉及到的字符编码问题零零散散,尤其是处理中文字符时一不留神就可能出现一堆奇奇怪怪的符号,俗称乱码. 对于乱码,究其原 ...

  9. Firefox火狐Flash插件卡死问题完美解决方法(转载)

    http://www.ihacksoft.com/firefox-flash-protectedmode.html 其实这个问题以前就出现过,而最近该问题又出现在最新的 Windows 8.1 系统中 ...

随机推荐

  1. Linux下mongodb安装及数据导入导出教程

    Linux下mongodb安装及数据导入导出教程 #查看linux发行版本 cat /etc/issue #查看linux内核版本号 uname -r 一.Linux下mongodb安装的一般步骤 1 ...

  2. 浅谈HTTP缓存以及后端,前端如何具体实现HTTP缓存

    <浅谈HTPP缓存>原版: https://juejin.im/post/5bdeabbbe51d4505466cd741?utm_source=gold_browser_extensio ...

  3. node.js 入门

    什么是Node.js?还服务器端javascript?对于这个概念我在这篇文章不做解释,可以自己去搜索了解下,服务器端js不是新技术,只是最近的node.js的火爆让他爆发了,我会在以后的文章里解释什 ...

  4. Editor编辑器的一些用法

    共有两个脚本,一个是有关Inspector面板的,一个是window的 using UnityEngine; using System.Collections; using UnityEditor; ...

  5. 同步(Sync)/异步(Async),阻塞(Block)/非阻塞(Unblock)四种调用方式

    1. 概念理解        在进行网络编程时,我们常常见到同步(Sync)/异步(Async),阻塞(Block)/非阻塞(Unblock)四种调用方式:   同步/异步主要针对C端: 同步:    ...

  6. Python踩坑:类与类对象类型参数传递与使用

    前言 对初学者来说,Python确实简单好用,毕竟动态类型语言,不用定义就可以拿来用,类型之间随意转换简直不要太方便,因此Python用来写写小脚本,爬虫程序什么的,没什么问题. 不过,一旦用来开发稍 ...

  7. 160824、ionic添加地图站点

    1.基本的地图显示 <!DOCTYPE html> <html ng-app="myApp"> <head> <meta charset= ...

  8. 0401-服务注册与发现、Eureka简介

    一.硬编码问题 解决方案:nginx.或.服务注册与发现 二.服务发现 注册.心跳机制 三.服务发现组件的功能 1.服务注册表:是一个记录当前可用服务实例的网络信息的数据库,是服务发现机制的核心.服务 ...

  9. Symfony 一些介绍

    Symfony 一些介绍: 路由:能限制 hostname,这就让有大量公共功能的网站可以共用一套代码:URI 识别支持 Reg 检测,让 url 能定义的随心所欲:支持前缀,import,便于模块化 ...

  10. Nginx图片及样式文件不记录访问日志

    1.Nginx作为web服务器是可直接在server配置文件中做如下配置: server { listen ; server_name www.fansik.com; access_log /data ...