您的位置:首页 > 编程语言 > C#

C#实现SOAP调用WebService

2014-06-16 10:41 309 查看
最近写了一个SOA服务,开始觉得别人拿到我的服务地址,然后直接添加引用就可以使用了,结果"大牛"告知不行。

让我写一个SOAP调用服务的样例,我有点愣了,因为没做过这方面的,于是搞到了一个Demo,然后学习了下。

 

学习如下:

在.Net中有一个对象:WebRequest它可以在后台直接请求服务的方法

第一步

 

var webRequest = (HttpWebRequest)WebRequest.Create(this.Uri);
webRequest.Headers.Add("SOAPAction", String.Format("\"{0}\"", this.SoapAction));
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
webRequest.Credentials = this.Credentials;


 

A:上述代码中,有一个SOAPAction,这个是你在IIS中部署好服务后,访问服务,如下图:



图中告知了使用者:SOAPAction:"http://tempuri.org/ProcessFlowRequest"

B:webRequest.Credentials = this.Credentials;

是调用服务的凭据

第二步

上述了解后,需要拼接SOAP请求的XML如图中看到的那个SOAP信息

<?xml version='1.0' encoding='utf-8'?>
<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
<soap:Body>
<{0} xmlns='{1}'>{2}</{0}>
</soap:Body>
</soap:Envelope>

把图片中对应的信息替换到{X}对应的位置,信息拼接就完成了!

第三步

var webRequest = (HttpWebRequest)WebRequest.Create(this.Uri);
webRequest.Headers.Add("SOAPAction", String.Format("\"{0}\"", this.SoapAction));
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
webRequest.Credentials = this.Credentials;

// 写入请求SOAP信息
using (var requestStream = webRequest.GetRequestStream())
{
using (var textWriter = new StreamWriter(requestStream))
{
var envelope = SoapHelper.MakeEnvelope(this.SoapAction, this.Arguments.ToArray());
}
}

// 获取SOAP请求返回
return webRequest.GetResponse();


 

这个就能获取到请求返回的XML!

 

其实用了才知道,原来很简单!

样例:

百度网盘: http://pan.baidu.com/s/1hquuXHa
CSDN: http://download.csdn.net/detail/hater22/7490147
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  .Net