2014-12-26 32 views
-1

我想從Powershell調用Google API。谷歌文檔說:使用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.

如何正確地轉換捲曲Invoke- WebRequest或其他PS cmdlet?

+0

另請參閱我在Powershell V3及更高版本中可用的「Invoke-RestMethod」。 – Eris

+1

但是,真正的問題在於,您將對象作爲一個主體傳遞。所有Google的API都需要這些參數,它們位於請求標題中,而不是主體。另外,你有沒有看過這個免費的PowerShell API實現https://github.com/squid808/gShell/ – Eris

回答

0

理論上你使用調用-的WebRequest權作爲POST請求的機構應具有應用程序/ x-WWW窗體-urlencoded這是默認的設置PS內容類型。

我執行相同的代碼,我得到了401請求,因爲我的auth參數不匹配。我也檢查了它的提琴手過,並構建正確

消息

礦小提琴手捕獲調用-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 

根據谷歌的OAuth樣本消息(https://developers.google.com/accounts/docs/OAuth2ForDevices)這是正確的,所以我也會檢查您在Fiddler的電話。