PowerShell小技巧之执行SOAP请求
SOAP的请求在WebService是无处不在的,像WCF服务和传统ASMXasp.net的webService。如果要测试SOAP服务是否好用通过web编程来实现就显得太过于复杂了,下面的脚本片段(snippet)将会轻而易举的完成通过powershell测试和调用SOAP服务:
这是一段程序代码。
functionExecute-SOAPRequest
(
[Xml] $SOAPRequest,
[String]$URL
)
{
write-host"SendingSOAPRequestToServer:$URL"
$soapWebRequest=[System.Net.WebRequest]::Create($URL)
$soapWebRequest.Headers.Add("SOAPAction","`"http://www.facilities.co.za/valid8service/valid8service/Valid8Address`"")
$soapWebRequest.ContentType="text/xml;charset=`"utf-8`""
$soapWebRequest.Accept ="text/xml"
$soapWebRequest.Method ="POST"
write-host"InitiatingSend."
$requestStream=$soapWebRequest.GetRequestStream()
$SOAPRequest.Save($requestStream)
$requestStream.Close()
write-host"SendComplete,WaitingForResponse."
$resp=$soapWebRequest.GetResponse()
$responseStream=$resp.GetResponseStream()
$soapReader=[System.IO.StreamReader]($responseStream)
$ReturnXml=[Xml]$soapReader.ReadToEnd()
$responseStream.Close()
write-host"ResponseReceived."
return$ReturnXml
}
$url='http://www.facilities.co.za/valid8service/valid8service.asmx'
$soap=[xml]@'
<?xmlversion="1.0"encoding="utf-8"?>
<soap12:Envelopexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<Valid8Addressxmlns="http://www.facilities.co.za/valid8service/valid8service">
<ID>string</ID>
<Address1></Address1>
<Address2></Address2>
<Address3></Address3>
<Address4></Address4>
<Address5></Address5>
<Address6></Address6>
<PostCode></PostCode>
</Valid8Address>
</soap12:Body>
</soap12:Envelope>
'@
$ret=Execute-SOAPRequest$soap$url
在这里得到的$ret变量中存储的是System.Xml.XmlDocument对象,如果需要查看其中的具体内容可以通过Export-Clixml这个cmdlet将其输出到本地文件中查看。
这是一段程序代码。
$ret|Export-Clixml c:\1.xml;Get-Contentc:\1.xml