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

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(‘呵呵’);
这个方法也有些麻烦的地方, 而且不支持文件的上传.

上一篇:持久化API(JPA)系列(三)实体Bean的开发技术-建立与数据库的连接


下一篇:linux命令之文件系统管理命令(下)