jjzjj

xml - Powershell Invoke-WebRequest 为 POST 准备 XML

coder 2024-07-02 原文

对于此处缺乏理解以及之前可能已经问过这个问题的可能性,提前致歉。我以为我通过移动到 Powershell v5.1 对它进行了排序,结果比我想象的要复杂,所以我会更新这个问题。

我们一直在 PS 4.0 版 上开发脚本,原因很明确,因为我们的客户拥有 PS v4.0 为标准的 Windows 2012 R2 服务器。但是,此脚本无法在 v4.x 上正常运行,如下所示

这是我的代码,带有正确形成的 xml 片段

$NETXNUA = "https://gate.sonile.com/ModSoap";
$ContentType = "text/xml";

# tried this and it this doesn't do anything
# [System.Net.ServicePointManager]::Expect100Continue = $false

$RequestBody = @"
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/1999/XMLSchema">
    <SOAP-ENV:Body>
        <sendMessage
        xmlns="http://gate.sonile.com/ModSoap" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
        <application xsi:type="xsd:string">RuFus</application>
        <password xsi:type="xsd:string">PingPong</password>
        <content xsi:type="xsd:string">Tiddles</content>
        <class xsi:type="xsd:string">mt_bubbles</class>
        </sendMessage>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
"@

try {
    $what = Invoke-WebRequest -Uri $NETXNUA -Method Post -Body $RequestBody -ContentType $ContentType -UseBasicParsing;
    }
catch {
    If ($_.Exception.Response.StatusCode.value__) {
    $crap = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim();
    Write-Output "crap $crap";
    }

    If  ($_.Exception.Response.StatusDescription) {
    $crapdescription = ($_.Exception.Response.StatusDescription).ToString().Trim();
    Write-Output "crapdesc $crapdescription";  
    }

    If  ($_.Exception.Message) {
    $crapMessage = ($_.Exception.Message).ToString().Trim();
    Write-Output "crapmsg $crapMessage";
    }

    If  ($_.ErrorDetails.Message) {
    $ResponseBody = ($_.ErrorDetails.Message).ToString().Trim();
    $ResponseBody = $ResponseBody -replace "\s+", " ";
    }

    Write-Output "default $ResponseBody";
}

这是我在 Windows 8.1 Pro 和标准 Powershell 上运行此脚本时发生的情况

Name                           Value                                                                                                          
----                           -----                                                                                                          
PSVersion                      4.0                                                                                                            
WSManStackVersion              3.0                                                                                                            
SerializationVersion           1.1.0.1                                                                                                        
CLRVersion                     4.0.30319.42000                                                                                                
BuildVersion                   6.3.9600.17400                                                                                                 
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}                                                                                           
PSRemotingProtocolVersion      2.2              

下面是结果,注意“$_.Exception.Message”是唯一有任何值的项目

crapmsg '"utf-8"' is not a supported encoding name. For information on 
defining a custom encoding, see the documentation for the Encoding.Regi
sterProvider method.
Parameter name: name

换句话说,惨败,信不信由你,Host处理了post数据

现在在装有更新的 v5.1 Powershell 的 Windows Server 2008 R2 上运行完全相同的脚本

Name                           Value                                                                                                            
----                           -----                                                                                                            
PSVersion                      5.1.14409.1005                                                                                                   
PSEdition                      Desktop                                                                                                          
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                          
BuildVersion                   10.0.14409.1005                                                                                                  
CLRVersion                     4.0.30319.42000                                                                                                  
WSManStackVersion              3.0                                                                                                              
PSRemotingProtocolVersion      2.3                                                                                                              
SerializationVersion           1.1.0.1

下面是“$_.Exception.Message”的结果

crapmsg Value cannot be null.
Parameter name: name

哇,这不一样,这是怎么回事..?

那么,让我们在更新了 Powershell v5.1 的 Windows Server 2012 R2 Azure VM 上再次尝试这个完全相同的脚本

Name                           Value                                                                                       
----                           -----                                                                                       
PSVersion                      5.1.14409.1005                                                                              
PSEdition                      Desktop                                                                                     
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                     
BuildVersion                   10.0.14409.1005                                                                             
CLRVersion                     4.0.30319.42000                                                                             
WSManStackVersion              3.0                                                                                         
PSRemotingProtocolVersion      2.3                                                                                         
SerializationVersion           1.1.0.1  

好了,结果与 2008 R2 服务器相同,只是“$_.Exception.Message”返回任何内容。至少这是一致的,因为 PS 版本相同。

crapmsg Value cannot be null.
Parameter name: name

如果我在 Windows 集合 Windows 10 家庭版 上使用标准安装的 Powershell v5.1 尝试这个脚本呢

Name                           Value                                                                                                                                                         
----                           -----                                                                                                                                                         
PSVersion                      5.1.14393.1358                                                                                                                                                
PSEdition                      Desktop                                                                                                                                                       
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                                                       
BuildVersion                   10.0.14393.1358                                                                                                                                               
CLRVersion                     4.0.30319.42000                                                                                                                                               
WSManStackVersion              3.0                                                                                                                                                           
PSRemotingProtocolVersion      2.3                                                                                                                                                           
SerializationVersion           1.1.0.1 

天哪,我不相信……奇迹!它与 $what 中返回的 200 响应以及我可以处理的 xml 中的主机响应完美配合。

StatusCode        : 200
StatusDescription : OK
Content           : <?xml version="1.0" encoding="UTF-8"?>
                    <tns1:Envelope 
xmlns:tns1="http://schemas.xmlsoap.org/soap/envelope/">...etc
RawContent        : HTTP/1.1 200 OK
                    Keep-Alive: timeout=15, max=100
                    Connection: Keep-Alive
                    Content-Length: 411
                    Content-Type: text/xml; charset="utf-8"
                    Date: Thu, 06 Jul 2017 04:02:15 GMT
                    Server: Apache
                    Via: 1.1 ga...
Forms             : 
Headers           : {[Keep-Alive, timeout=15, max=100], [Connection, Keep-
Alive], [Content...etc
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : 
RawContentLength  : 411

如果我的客户抛弃他们喜欢的那些讨厌的 Windows 服务器并改用 Windows 10,一切都会完全解决......!

突发新闻!刚刚尝试了 Windows Server 2016 Azure VM,它也运行良好。

Name                           Value                                                                                               
----                           -----                                                                                               
PSVersion                      5.1.14393.479                                                                                       
PSEdition                      Desktop                                                                                             
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                             
BuildVersion                   10.0.14393.479                                                                                      
CLRVersion                     4.0.30319.42000                                                                                     
WSManStackVersion              3.0                                                                                                 
PSRemotingProtocolVersion      2.3                                                                                                 
SerializationVersion           1.1.0.1  

是否有一些 secret 参数可以使这个脚本在各种平台和版本的 Powershell 上正常工作......?

我使用 Invoke-WebRequest 创建的所有其他脚本在 PS v4 和 v5 上都运行良好,只是这个导致了问题。

感谢接受任何提示

以前我尝试使用 xml 的文件输入并像这样使用 -InFile 读取......

Invoke-WebRequest "https://gateway.mobil.com/MSoap" -Method Post -ContentType "text/xml" -InFile "C:\Scripts\mobil.xml" -OutFile "C:\PWScripts\mobil_out.xml"

效果不错,但不适合我的应用

最佳答案

整个星期都在这个脚本上辛勤工作了无数个小时......奇怪的是,它只在成功返回 200 状态时失败,错误返回得很好!

事实证明,Invoke-WebRequest 有一个无法解决的问题,@vane 在 2016 年 4 月发布了这个问题Why is Invoke-WebRequest and Invoke-RestMethod failing and succeeding at the same time?

因此,如果我错了,请纠正我,唯一已知的解决方案是恢复为标准的 http WebRequest 调用(用您自己的错误处理包装它);

    $encodedContent = [System.Text.Encoding]::UTF8.GetBytes($RequestBody)

    $webRequest = [System.Net.WebRequest]::Create($NETXNUA)

    $webRequest.Method = "Post"
    $webRequest.ContentType = $ContentType
    $webRequest.ContentLength = $encodedContent.length

    $requestStream = $webRequest.GetRequestStream()
    $requestStream.Write($encodedContent, 0, $encodedContent.length)
    $requestStream.Close()

    [System.Net.WebResponse] $response = $webRequest.GetResponse();

我已经验证了这种旧式机制在以下平台上完美运行;

Win 8.1 Pro with PS v4.0
Server 2008 R2 with PS 5.1
Server 2012 R2 with PS 5.1 (Azure VM)
Server 2012 R2 with PS v4.0 (Azure VM)
Win 10 Home with PS 5.1 
Server 2016 with PS v5.1 (Azure VM)

我承认 Invoke-WebRequest 脚本在 Win 10 和 Server 2016 上运行完美,所以最终问题会消失!

两年后,2019 年 11 月:奇怪的发现..!

已将设备更新到 Windows 10 版本 1903 并开始运行脚本。

立即发现任何使用 Invoke-WebRequest 的脚本都不起作用。

错误是由未完成的 Internet Explorer 安装引起的。

已安装 IE,Invoke-WebRequest 运行正常。

道德:你永远无法完全摆脱 IE

关于xml - Powershell Invoke-WebRequest 为 POST 准备 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44858618/

有关xml - Powershell Invoke-WebRequest 为 POST 准备 XML的更多相关文章

  1. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  2. ruby - 如何模拟 Net::HTTP::Post? - 2

    是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou

  3. ruby-on-rails - rails : How to make a form post to another controller action - 2

    我知道您通常应该在Rails中使用新建/创建和编辑/更新之间的链接,但我有一个情况需要其他东西。无论如何我可以实现同样的连接吗?我有一个模型表单,我希望它发布数据(类似于新View如何发布到创建操作)。这是我的表格prohibitedthisjobfrombeingsaved: 最佳答案 使用:url选项。=form_for@job,:url=>company_path,:html=>{:method=>:post/:put} 关于ruby-on-rails-rails:Howtomak

  4. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

  5. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  6. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  7. ruby-on-rails - 如何通过 POST 发送多个相同的键/参数? - 2

    如果我必须在一个HTTP请求中发送一堆post参数,所有这些参数都具有相同的名称,我该如何构建要发布的data对象?想象一个带有一些复选框的表单,它们都具有相同的name属性但具有不同的值(如果它们被选中):我想用ruby​​构建它(但它需要根据在表单上选择的内容动态创建):data={"color"=>"red","color"=>"green","color"=>"blue"}然后将数据发送到某个URL:Net::HTTP.post_form(url,data)我无法控制接收端,所以我必须发送它期望接收的参数。怎么办? 最佳答案

  8. ruby-on-rails - 如何在 Rails 3 中禁用 XML 解析 - 2

    我想禁用HTTP参数的自动XML解析。但我发现命令仅适用于Rails2.x,它们都不适用于3.0:config.action_controller.param_parsers.deleteMime::XML(application.rb)ActionController::Base.param_parsers.deleteMime::XMLRails3.0中的等价物是什么? 最佳答案 根据CVE-2013-0156的最新安全公告你可以将它用于Rails3.0。3.1和3.2ActionDispatch::ParamsParser::

  9. ruby - 如何使用 Nokogiri::XML::Builder 生成动态标签? - 2

    我正在遍历数组中的一组标签名称,我想使用构建器打印每个标签名称,而不是求助于“我认为:builder=Nokogiri::XML::Builder.newdo|xml|fortagintagsxml.tag!tag,somevalendend会这样做,但它只是创建名称为“tag”的标签,并将标签变量作为元素的文本值。有人可以帮忙吗?这个看起来应该比较简单,我刚刚在搜索引擎上找不到答案。我可能没有以正确的方式提问。 最佳答案 尝试以下操作。如果我没记错的话,我添加了一个根节点,因为Nokogiri需要一个。builder=Nokogi

  10. ruby - HTTP POST 上的 SSL 错误(未知协议(protocol)) - 2

    尝试通过SSL连接到ImgurAPI时出现错误。这是代码和错误:API_URI=URI.parse('https://api.imgur.com')API_PUBLIC_KEY='Client-ID--'ENDPOINTS={:image=>'/3/image',:gallery=>'/3/gallery'}#Public:Uploadanimage##args-Theimagepathfortheimagetoupload#defupload(image_path)http=Net::HTTP.new(API_URI.host)http.use_ssl=truehttp.verify

随机推荐