【问题标题】:How to create a raw body for POST request using PowerShell如何使用 PowerShell 为 POST 请求创建原始正文
【发布时间】:2016-03-02 13:35:29
【问题描述】:

我正在尝试使用 PowerShell 的 POST 请求。它需要原始类型的主体。我知道如何使用 PowerShell 传递表单数据,但不确定原始数据类型。对于 Postman 中的简单原始数据,例如

{
"@type":"login",
 "username":"xxx@gmail.com",
 "password":"yyy"
}

我在 PowerShell 中通过下面,它工作正常。

$rawcreds = @{
               '@type' = 'login'
                username=$Username
                password=$Password
             }

        $json = $rawcreds | ConvertTo-Json

但是,对于如下所示的复杂原始数据,我不确定如何传入 PowerShell。

{
    "@type": Sample_name_01",
    "agentId": "00000Y08000000000004",
    "parameters": [
        {
            "@type": "TaskParameter",
            "name": "$source$",
            "type": "EXTENDED_SOURCE"
        },
        {
            "@type": "TaskParameter",
            "name": "$target$",
            "type": "TARGET",
            "targetConnectionId": "00000Y0B000000000020",
            "targetObject": "sample_object"
        }
    ],
    "mappingId": "00000Y1700000000000A"
}

【问题讨论】:

  • Invoke-WebRequestInvoke-RestMethod-Body 参数接受一个字符串,并将其用作“原始正文”,所以我不确定我是否理解这个问题。
  • 你的意思是,我可以通过下面给出的整个原始身体?
  • 将所需的文字(原始)内容放入字符串中,然后将其传入。在第一个示例中,您创建一个对象,然后将其转换为 JSON(字符串)。您的“复杂”示例是否意味着原始 JSON?而你不确定如何构建它?
  • 是的,没错。

标签: rest powershell powershell-5.0


【解决方案1】:

我的解释是,您的第二个代码块是您想要的原始 JSON,而您不确定如何构造它。最简单的方法是使用here string:

$body = @"
{
    "@type": Sample_name_01",
    "agentId": "00000Y08000000000004",
    "parameters": [
        {
            "@type": "TaskParameter",
            "name": "$source$",
            "type": "EXTENDED_SOURCE"
        },
        {
            "@type": "TaskParameter",
            "name": "$target$",
            "type": "TARGET",
            "targetConnectionId": "00000Y0B000000000020",
            "targetObject": "sample_object"
        }
    ],
    "mappingId": "00000Y1700000000000A"
}
"@

Invoke-WebRequest -Body $body

变量替换有效(因为我们使用了@" 而不是@'),但您不必对文字" 字符进行混乱的转义。

这意味着$source$ 将被解释为一个名为$source 的变量,将嵌入到字符串中,后跟文字$。如果这不是您想要的(也就是说,如果您想在正文中直接使用 $source$),则使用 @''@ 将您的 here 字符串括起来,以便不嵌入 powershell 变量。

【讨论】:

  • 感谢您提供详细信息。它很有帮助。是的,我想从字面上使用 $source$。正如你提到的,我会使用@'$source$'@。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 2010-11-06
  • 2015-12-02
  • 2018-09-21
  • 1970-01-01
  • 2016-02-11
相关资源
最近更新 更多