REST API失败:Invoke-WebRequest:404 [英] REST API failure: Invoke-WebRequest : 404

本文介绍了REST API失败:Invoke-WebRequest:404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的Powershell代码将值写入和读取到Google表格(可以正常工作),并且应该使用API​​在Apps脚本项目中运行函数myfunction,但是Invoke-WebRequest返回以下错误:

The Powershell code bellow writes and reads values to Google Sheets (works fine) and should run the function myfunction in an Apps Script project using API, but Invoke-WebRequest returns the error bellow:

Invoke-WebRequest : 404. That’s an error. The requested URL /v1/scripts/=ya29.a0Ae4lvC3k8aahOCPBgf-tRf4SRFxdcCE97fkbXLAJqZ4zRCLnBp9prwEcBYBAf
lYP6zyW3fLeD3u4iSw5jYtDAdgZiSsTjzQbCpj9e_ahCA0xwC_1NBTjYkPwqFdLli7LNpfFcuedFDhdUpfnKTRZdbBWIf2ZyxyuGc6p was not found on this server. That’s 
all we know.
No C:\Users\F76254C\Desktop\Nova pasta\Batch files\Available Projects\Latam HIL Lab Menu\libs\Google\WriteToGoogleSheets.ps1:64 caractere:13
+     $resp = Invoke-WebRequest -Uri "https://script.googleapis.com/v1/ ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

我不确定请求主体的JSON表示是否设置正确,还是由于其他原因导致了错误.

I am not sure if the JSON representation of request body is set correctly or if the error was caused for something else.

Powershell代码:

Powershell Code:

function doit{
    $json = ".\client_id.json"
    $jdata = get-content $json | convertfrom-json
    <#
    $jdata | ForEach-Object {
        $_.PSObject.Properties.Value
    }
    #>
    $ClientID = $jdata.web.client_id.ToString()
    $ClientSecret = $jdata.web.client_secret.ToString()
    $refreshToken = "1//04VvG_FTyDGhiCgYIARAAGAQSNwF-L9IrZ-o1kaZQQccvzL5m4TUTNz6b9Q4KCb16t4cH11gGCshWZWvgaCoMlg73FgpLAGOYTEk" 
    $grantType = "refresh_token" 
    $requestUri = "https://accounts.google.com/o/oauth2/token" 
    $GAuthBody = "refresh_token=$refreshToken&client_id=$ClientID&client_secret=$ClientSecret&grant_type=$grantType" 
    $GAuthResponse = Invoke-RestMethod -Method Post -Uri $requestUri -ContentType "application/x-www-form-urlencoded" -Body $GAuthBody


    $accessToken = $GAuthResponse.access_token

    $headers = @{"Authorization" = "Bearer $accessToken"          

                  "Content-type" = "application/json"}

    $DocumentID = "1htbeGlqZ4hojQBWl9fxE4nW_KZI9uVwi0ApzNOIbwnY"

    $currentDate = (Get-Date).ToString('MM/dd/yyyy')
    $currentTime = (Get-Date).ToString('HH:mm:sstt')

$json = @"
{
    "range": "HIL_APP!A1:G1",
    "majorDimension": "ROWS",
    "values":
                [[
                    "HIL_NAME",
                    "$env:ComputerName",
                    "$currentDate",
                    "$currentTime",
                    "$env:UserName",
                    "input from user",
                    "attempt"
                ],]
}
"@

    $write = Invoke-WebRequest -Uri "https://sheets.googleapis.com/v4/spreadsheets/$DocumentID/values/HIL_APP!A1:G1:append?valueInputOption=USER_ENTERED&access_token=$($accessToken)" -Method Post -ContentType "application/json" -Body $json
    $read = Invoke-WebRequest -Uri "https://sheets.googleapis.com/v4/spreadsheets/$DocumentID/values/HIL_APP!A1:G1?access_token=$($accessToken)"
    Write-Output "Response: " ($read.Content | ConvertFrom-Json)

$scriptId = "1eF7ZaHH-pw2-AjnRVhOgnDxBUpfr0wALk1dVFg7B220bg_KuwVudbALh"

$json = @"
{
  "function": "myfunction",
  "parameters": [
    "attempt" string
  ],
  "devMode": true
}
"@

    $resp = Invoke-WebRequest -Uri "https://script.googleapis.com/v1/scripts/$scriptId:run?access_token=$($accessToken)" -Method Post -ContentType "application/json" -Body $json
#    Write-Output "Response: " ($resp.Content | ConvertFrom-Json)
}

clear

doit

Google App脚本代码:

Google App Script code:

function toSpreadsheet(text2write)
  {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("HIL_APP");

  for (var i = 1; i < sheet.getLastRow(); i++)
  {
    sheet.getRange(i+1, 8, 1).setValue(text2write)
  }
  return "myreturn"
}

function myfunction(params)
{
  toSpreadsheet(params)
}

推荐答案

  • 您可以确认用于写入和读取Google表格值的脚本可以正常工作.
  • 您只想修改用于使用Apps Script API运行Google Apps脚本的脚本.
    • 您已经可以使用Apps Script API.
    • 您的访问令牌可用于运行Google Apps脚本.
      • You could confirm that the script for writing and reading values for Google Sheets worked fine.
      • You want to modify only the script for running the Google Apps Script using Apps Script API.
        • You have already been able to use Apps Script API.
        • Your access token can be used for running the Google Apps Script.
        • 如果我的理解是正确的,那么这个答案如何?请认为这只是几个可能的答案之一.

          If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

          • 从您的错误消息和脚本中,我想提出以下修改要点.
          • From your error message and your script, I would like to propose the following modification points.
          1. "https://script.googleapis.com/v1/scripts/$scriptId:run?access_token=$($accessToken)""https://script.googleapis.com/v1/scripts/${scriptId}:run"
            • 在您的脚本中,端点为https://script.googleapis.com/v1/scripts/.这是不完整的终点.
            • 我认为您当前错误消息的原因是由于此原因.
          1. From "https://script.googleapis.com/v1/scripts/$scriptId:run?access_token=$($accessToken)" to "https://script.googleapis.com/v1/scripts/${scriptId}:run"
            • In your script, the endpoint is https://script.googleapis.com/v1/scripts/. This is incomplete endpoint.
            • I think that the reason of your current error message is due to this.
          • 我认为使用Sheets API也可以这样说.

          修改了脚本中对Apps Script API的请求后,它如下所示.

          When the request to Apps Script API in your script is modified, it becomes as follows.

          $scriptId = "1eF7ZaHH-pw2-AjnRVhOgnDxBUpfr0wALk1dVFg7B220bg_KuwVudbALh"
          
          $json = @"
          {
            "function": "myfunction",
            "parameters": ["attempt"],
            "devMode": true
          }
          "@
          
          $resp = Invoke-WebRequest -Uri "https://script.googleapis.com/v1/scripts/${scriptId}:run" -Method Post -ContentType "application/json" -Body $json -Headers @{"Authorization"="Bearer ${accessToken}"}
          

          注意:

          • 在我的环境中,我可以确认上述修改后的脚本有效.遗憾的是,我无法理解您设置使用Apps Script API运行Google Apps脚本的流程.因此,如果在您的环境中发生错误,请再次确认使用Apps Script API运行脚本的设置.
          • 我认为"Bearer ${accessToken}"也可以修改为"Bearer $accessToken".
          • Note:

            • In my environment, I could confirm that above modified script worked. Unfortunately, I cannot understand about your flow for setting to run the Google Apps Script with Apps Script API. So if in your environment, an error occurs, please confirm the settings for running the script with Apps Script API, again.
            • I think that "Bearer ${accessToken}" can be also modified to "Bearer $accessToken".
            • 如果我误解了您的问题,而这不是您问题的直接解决方案,我深表歉意.

              If I misunderstood your question and this was not the direct solution of your issue, I apologize.

              这篇关于REST API失败:Invoke-WebRequest:404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆