1

我无法使用 PowerShell(Windows 运行程序)从 YML Gitlab Pipeline 提交 Dropbox API 请求。API 需要将 JSON 作为标头参数传递,并且将该 JSON 编码到 YML Gitlab Pipeline 中不起作用:

`--header "Dropbox-API-Arg:{\"path\":\"/$BUILD_FILENAME\"}"

完整的脚本步骤如下,因为它现在在 YML 中定义:

- C:\Windows\System32\curl.exe -X POST https://content.dropboxapi.com/2/files/upload --header "Authorization:Bearer $DROPBOX_TOKEN" --header "Content-Type:application/octet-stream" --header "Dropbox-API-Arg:{\"path\":\"/$BUILD_FILENAME\"}" --data-binary @$BUILD_FULLFILENAME

响应错误如下:

Error in call to API function "files/upload": HTTP header "Dropbox-API-Arg": could not decode input as JSONcurl: (3) Port number ended with '\'

我可以在运行者所在的同一台 PC 上的 Windows PowerShell 中执行上述命令,而不会出现任何问题:

curl -X POST https://content.dropboxapi.com/2/files/upload --header "Authorization: Bearer XXX" --header "Dropbox-API-Arg: {\"path\": \"/README.md\"}" --header "Content-Type: application/octet-stream" --data-binary @README.md

如何正确编码 JSON 以便它可以按预期执行并传递给 CURL?

4

1 回答 1

1

我认为以下应该有效。它使用--%它来阻止 PowerShell 在调用时解析 curl 命令的参数$fullCommand。这允许在Dropbox-API-Arg标题中保留双引号。

$fullCommand = 'C:\Windows\System32\curl.exe --%'
$fullCommand += ' -X POST https://content.dropboxapi.com/2/files/upload'
$fullCommand += ' --header "Authorization:Bearer ' + $DROPBOX_TOKEN + '"'
$fullCommand += ' --header "Content-Type:application/octet-stream"'
$fullCommand += ' --header "Dropbox-API-Arg:{\"path\":\"' + $BUILD_FILENAME + '\"}"'
$fullCommand += ' --data-binary @' + $BUILD_FULLFILENAME
Invoke-Expression $fullCommand

现场演示

.gitlab-ci.yml

stages:
  - run_on_windows_test

run_on_windows_test_1:
  stage: run_on_windows_test
  tags:  
  - shared-windows
  - windows
  - windows-1809

  variables:
    DROPBOX_TOKEN: "THE_TOKEN"
    BUILD_FILENAME: "test.txt"
    BUILD_FULLFILENAME: C:\Windows\TEMP\test.txt
  
  script:
    - fsutil file createnew C:\Windows\TEMP\test.txt 128
    - $fullCommand = 'C:\Windows\System32\curl.exe --% '
    - $fullCommand += '-X POST https://requestinspector.com/inspect/01ems2t2f0r4dkfyzk1d820e1t'
    - $fullCommand += ' --header "Authorization:Bearer ' + $DROPBOX_TOKEN + '"'
    - $fullCommand += ' --header "Content-Type:application/octet-stream"'
    - $fullCommand += ' --header "Dropbox-API-Arg:{\"path\":\"' + $BUILD_FILENAME + '\"}"'
    - $fullCommand += ' --data-binary @' + $BUILD_FULLFILENAME
    - Invoke-Expression $fullCommand
    - $fullCommand = 'C:\Windows\System32\curl.exe --% '
    - $fullCommand += '-X POST http://requestbin.net/r/1b135t41'
    - $fullCommand += ' --header "Authorization:Bearer ' + $DROPBOX_TOKEN + '"'
    - $fullCommand += ' --header "Content-Type:application/octet-stream"'
    - $fullCommand += ' --header "Dropbox-API-Arg:{\"path\":\"' + $BUILD_FILENAME + '\"}"'
    - $fullCommand += ' --data-binary @' + $BUILD_FULLFILENAME
    - Invoke-Expression $fullCommand

工作成果

请求检查员结果

RequestBin 结果

于 2020-10-16T16:23:44.133 回答