访问https加密的WebServices方法
访问https加密的WebServices方法
一
获取该webservices的wsdl描述文档
可以通过安装证书的浏览器访问获得,也可以通过以下代码将获得wsdl文档存入指定的磁盘下。
static void Main(string[] args)
{
string msg;
string str = GetWsdl("https://localhost/MyWebServices.asmx?WSDL", null, "Get", out msg);
using (FileStream fs=new FileStream ("d:/1.wsdl",FileMode.CreateNew))
{
using (StreamWriter sw=new StreamWriter (fs))
{
sw.Write(str);
}
}
}
public static string GetWsdl(string url, string arges, string method, out string msg)
{
string getData = string.Empty;
try
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
HttpWebRequest httpRequest = null;
if (method.ToUpper() == "GET")
{
if (!string.IsNullOrEmpty(arges))
{
url = url + "?" + arges;
}
httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
X509Certificate cerCaiShang = new X509Certificate("Cer\\ssl.pfx", "1234");
httpRequest.ClientCertificates.Add(cerCaiShang);
}
if (method.ToUpper() == "POST")
{
httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
X509Certificate cerCaiShang = new X509Certificate("Cer\\ssl.pfx", "1234");
httpRequest.ClientCertificates.Add(cerCaiShang);
byte[] bs = Encoding.UTF8.GetBytes(arges);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
if (!string.IsNullOrEmpty(arges))
{
httpRequest.ContentLength = bs.Length;
using (Stream reqStream = httpRequest.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}
}
}
// Stream stream = null;
using (HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse())
{
// stream= response.GetResponseStream();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
getData = reader.ReadToEnd().ToString();
}
}
msg = null;
return getData;
}
catch (Exception ex)
{
msg = ex.ToString();
return null;
}
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
二 将获得的wsdl文件通过wsdl.exe手动生产代理类
wsdl /l:cs /n:tt /out:d:\2.cs d:\1.wsdl
参数解释 /l 代表开发语言后缀名
/n 生成的代码文件的命名空间
/out 生产文件的路径 以及wsdl文档所在的路径
三将生产的代理类引入到项目中,并在构造函数中加入以下代码
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
X509Certificate cerCaiShang = new X509Certificate("Cer\\ssl.pfx", "1234");//证书所在的路径及密码
this.ClientCertificates.Add(cerCaiShang);
在代理类中加入以下代码
private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
现在就可以通过代理类访问加密后的webservices了
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。