无法写入 Google 工作表((400)错误请求)

Unable to write to Google Sheets ((400) Bad Request)

我正在尝试使用 API 和 PowerShell 网络请求写入私人 Google 表格文档。我知道我已经正确处理了身份验证,因为我可以使用以下代码从 sheet 读取内容:

$read = Invoke-WebRequest -Uri "https://sheets.googleapis.com/v4/spreadsheets/$sheet/values/Sheet1!A1:B2?access_token=$($token.access_token)"

当我尝试写入相同的 sheet 时出现问题(在清除单元格中的所有内容之后):

$json = @”
{
  "range": "Sheet1!A1:D2",
  "majorDimension": "ROWS",
  "values": [
    ["Door", "15", "2", "3/15/2016"],
    ["Engine", "100", "1", "3/20/2016"]
  ]
}
“@

Invoke-WebRequest -Uri "https://sheets.googleapis.com/v4/spreadsheets/$sheet/values/Sheet1!A1:D2:append?valueInputOption=USER_ENTERED&access_token=$($token.access_token)" -Method Post -Body $json

我得到:

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

我做错了什么?

您的 Invoke-WebRequest 缺少 ContentType 参数,当您的 Method 设置为发送数据的动词时(例如 Post),这是必需的。

The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.

The Content-Type Header Field

在您的情况下,参数将为 -ContentType "application/json"。例如:

Invoke-WebRequest -Uri "https://sheets.googleapis.com/v4/spreadsheets/$sheet/values/Sheet1!A1:D2:append?valueInputOption=USER_ENTERED&access_token=$($token.access_token)" -Method Post -ContentType "application/json" -Body $json 

Invoke-WebRequest ContentType Documentation