【问题标题】:Trying to make a API call to get token尝试进行 API 调用以获取令牌
【发布时间】:2019-05-24 17:54:32
【问题描述】:

以下是我尝试为令牌进行 API 调用的代码。似乎 x-www-form-urlencoded 在转换为 body 时导致 401 未经授权。将 body 转换为 x-www-form-urlencoded 的标准过程是什么。

Add-Type @"
    using System;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    public class ServerCertificateValidationCallback
    {
        public static void Ignore()
        {
            ServicePointManager.ServerCertificateValidationCallback += 
                delegate
                (
                    Object obj, 
                    X509Certificate certificate, 
                    X509Chain chain, 
                    SslPolicyErrors errors
                )
                {
                    return true;
                };
        }
    }
"@
[ServerCertificateValidationCallback]::Ignore();

$header = @{
 "content-Type"="application/x-www-form-urlencoded"
 "accept"="application/json"
}

$APICURL= "myurl" 

$json = @{ "grant_type"="access"
         "client_id" = "xyz"
         "client_secret" = "abc"
        "scope" = "one"}


         $body = $json | ConvertTo-Json
          $response =Invoke-Restmethod -Uri $APICURL -Method Post -Headers $header -Body $body

【问题讨论】:

  • 默认情况下,POST 中的 Content-Type 是 application/x-www-form-urlencoded。我会从标题中删除它。

标签: json powershell api http type-conversion


【解决方案1】:

您已将 Content-Type 设置为 x-www-form-urlencoded,但您提供的是 JSON。 JSON 作为一种主体类型非常常见,因此我首先尝试将您的 Content-Type 更新为 application/json,除非您确定规范要求 x-www-form-urlencoded。

如果是后者,你可能想看看这个问题:How to Post Request with Invoke-WebRequest

【讨论】:

  • 如何提供 x-www-form-urlencoded 而不是 JSON?
  • 有没有办法可以将我的 JSON 正文转换为 x-www-form-urlencoded
  • 如果我提供的链接不适合你,你可以使用这个:geekeefy.wordpress.com/2017/05/26/…
【解决方案2】:

将内容类型更改为应用程序/json。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 2016-07-26
    • 2020-06-09
    相关资源
    最近更新 更多