无需 WSDL 即可使用 SAP PI Web 服务






3.50/5 (2投票s)
本技巧提供了一种非常基础/简单的实现方法,用于与授权接收方的 SAP PI Web 服务进行交互。
引言
如果您需要使用 SAP PI Web 服务,这里提供了一种可行的且非常简单的方法,无需 WSDL 或在您的 .NET 解决方案中添加任何服务引用即可连接到 Web 服务。
背景
我在一个项目中遇到一个需求,需要连接到客户端位置托管的 SAP PI Web 服务,但无法从客户端获取相关的 WSDL 文件/信息,只能获取端点 URL。因此,使用 HttpWebRequest
,我尝试连接到 Web服务
,并获得了如下部分所述的响应。
Using the Code
通过提供 SOAP 包裹头并创建 Web 服务 POST
请求的正文(需要作为输入发送到 Web 服务)来创建 HttpWebRequest
对象。
HttpWebRequest request = CreateWebRequest();
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(@"<?xml version=""1.0""
encoding=""utf-8""?>
<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:inv=""http://SpecificURL"">
<soapenv:Body>
<AnyTag>...</AnyTag>
</soapenv:Body>
</soapenv:Envelope>");
创建一个 private
方法 CreateWebRequest
,用于填充 Web 请求头相关的属性/信息。
private static HttpWebRequest CreateWebRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create
(@"WebServiceEndPointURL
");
webRequest.Headers.Add(@"SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
string authorization = "username
" +
":" + "password
";
byte[] binaryAuthorization = System.Text.Encoding.UTF8.GetBytes(autorization);
authorization = Convert.ToBase64String(binaryAuthorization);
authorization = "Basic " + authorization;
webRequest.Headers.Add("AUTHORIZATION", authorization);
return webRequest;
}
使用以下代码与 SAP PI Web 服务进行交互。以下代码中提到的 Catch
部分将帮助您识别问题的确切根本原因,如果 Web 服务托管在不同的环境中,这将非常有用。
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
<here you can write the business logic implementation>
}
}
}
catch (Exception e)
{
if (e is WebException && ((WebException)e).Status == WebExceptionStatus.ProtocolError)
{
WebResponse errResp = ((WebException)e).Response;
using (Stream respStream = errResp.GetResponseStream())
{
using (StreamReader rd = new StreamReader(respStream))
{
string soapResult = rd.ReadToEnd();
}
}
}
}