gpt4 book ai didi

rest - Powershell v3 Invoke-RestMethod header

转载 作者:行者123 更新时间:2023-12-04 11:39:27 24 4
gpt4 key购买 nike

我正在尝试对服务进行 RestAPI 调用,该服务在其文档中指定以下内容:

An Integration Server can respond in XML and JSON formats. Use one of the following accept headers in your requests:

  1. accept: application/json, /.
  2. accept: application/xml, /

If the accept header does not include application/xml, application/json or /, the integration server will respond with a "406 method not acceptable" status code.



我的 powershell 代码如下所示 Invoke-RestMethod -URI https://URL/ticket -Credential $cred -Method Get -Headers @{"Accept"="application/xml"}
但是我收到与标题相关的以下错误: Invoke-RestMethod : This header must be modified using the appropriate property or method.
Parameter name: name

有人可以帮助我理解为什么 powershell 不允许我指定 Accept header 吗?还是我在这里缺少另一种方法?

谢谢

最佳答案

Accept header could not be specified两者都不是 Invoke-RestMethod也不是 Invoke-WebRequest在PowerShell V3中,你可以考虑下面的函数,在一定程度上模拟Invoke-RestMethod :

Function Execute-Request()
{
Param(
[Parameter(Mandatory=$True)]
[string]$Url,
[Parameter(Mandatory=$False)]
[System.Net.ICredentials]$Credentials,
[Parameter(Mandatory=$False)]
[bool]$UseDefaultCredentials = $True,
[Parameter(Mandatory=$False)]
[Microsoft.PowerShell.Commands.WebRequestMethod]$Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Get,
[Parameter(Mandatory=$False)]
[Hashtable]$Header,
[Parameter(Mandatory=$False)]
[string]$ContentType
)

$client = New-Object System.Net.WebClient
if($Credentials) {
$client.Credentials = $Credentials
}
elseif($UseDefaultCredentials){
$client.Credentials = [System.Net.CredentialCache]::DefaultCredentials
}
if($ContentType) {
$client.Headers.Add("Content-Type", $ContentType)
}
if($Header) {
$Header.Keys | % { $client.Headers.Add($_, $Header.Item($_)) }
}
$data = $client.DownloadString($Url)
$client.Dispose()
return $data
}

例子:
Execute-Request -Url "https://URL/ticket" -UseDefaultCredentials $true

Execute-Request -Url "https://URL/ticket" -Credentials $credentials -Header @{"Accept" = "application/json"} -ContentType "application/json"

关于rest - Powershell v3 Invoke-RestMethod header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18278977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com