欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PowerShell小技巧之执行SOAP请求

程序员文章站 2022-03-29 21:50:17
soap的请求在web service是无处不在的,像wcf服务和传统asmx asp.net的web service。如果要测试soap服务是否好用通过web编程来实现就...

soap的请求在web service是无处不在的,像wcf服务和传统asmx asp.net的web service。如果要测试soap服务是否好用通过web编程来实现就显得太过于复杂了,下面的脚本片段(snippet)将会轻而易举的完成通过powershell测试和调用soap服务:

这是一段程序代码。

复制代码 代码如下:

function execute-soaprequest
(
        [xml]    $soaprequest,
        [string] $url
)
{
        write-host "sending soap request to server: $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 "initiating send."
        $requeststream = $soapwebrequest.getrequeststream()
        $soaprequest.save($requeststream)
        $requeststream.close()
       
        write-host "send complete, waiting for response."
        $resp = $soapwebrequest.getresponse()
        $responsestream = $resp.getresponsestream()
        $soapreader = [system.io.streamreader]($responsestream)
        $returnxml = [xml] $soapreader.readtoend()
        $responsestream.close()
       
        write-host "response received."
        return $returnxml
}
$url = 'http://www.facilities.co.za/valid8service/valid8service.asmx'
$soap = [xml]@'
<?xml version="1.0" encoding="utf-8"?>
<soap12:envelope xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns:soap12="">
  <soap12:body>
    <valid8address xmlns="">
      <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-content c:\1.xml