【问题标题】:Call Google API with Powershell使用 Powershell 调用 Google API
【发布时间】:2014-12-27 09:49:46
【问题描述】:

我想从 Powershell 调用 Google API。谷歌文档说:

curl "https://accounts.google.com/o/oauth2/token" 
  -d "client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&code=$CODE&grant_type=authorization_code&redirect_uri=urn:ietf:wg:oauth:2.0:oob"

从命令行执行时有效。

我尝试将其转换为 powershell,例如:

$token = Invoke-WebRequest -Uri "https://accounts.google.com/o/oauth2/token" -Method POST -Body "client_id=x&client_secret=y&code=z&grant_type=authorization_code&redirect_uri=urn:ietf:wg:oauth:2.0:oob"

比如:

$tokenParams = @{
  client_id='x';
  client_secret='y';
  code='z';
  grant_type='authorization_code';
  redirect_uri='urn:ietf:wg:oauth:2.0:oob'
}

$token = Invoke-WebRequest -Uri "https://accounts.google.com/o/oauth2/token" -Method POST -Body $tokenParams

两者都返回:

Invoke-WebRequest : The remote server returned an error: (400) Bad Request.

如何正确地将 curl 转换为 Invoke-WebRequest 或其他 PS cmdlet?

【问题讨论】:

  • 还可以查看Invoke-RestMethod,我在 Powershell V3 及更高版本中可用。
  • 但是,这里真正的问题是您将对象作为一个主体传递。 Google 的所有 API 都希望这些作为参数,它们位于请求标头中,而不是正文中。另外,你有没有看过这个免费的 powershell API 实现 github.com/squid808/gShell

标签: powershell curl


【解决方案1】:

理论上你使用 Invoke-WebRequest 是正确的,因为 POST 请求的主体应该有 application/x-www-form-urlencoded 内容类型,这是在 PS 中默认设置的。

我执行了相同的代码并收到了 401 请求,因为我的身份验证参数不匹配。我也在 Fiddler 中检查过,消息构造正确

Mine Fiddler 捕获的 Invoke-WebRequest POST 消息如下所示:

POST https://accounts.google.com/o/oauth2/token HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT; Windows NT 6.4; hu-HU) WindowsPowerShell/5.0.9879.0
Content-Type: application/x-www-form-urlencoded
Host: accounts.google.com
Content-Length: 113
Expect: 100-continue
Connection: Keep-Alive

grant_type=authorization_code&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&code=z&client_id=x&client_secret=y

根据 Google 的 oauth 示例消息 (https://developers.google.com/accounts/docs/OAuth2ForDevices),这是正确的,所以我也会检查您在 Fiddler 中的调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    相关资源
    最近更新 更多