如何在收到 'httpStatus 400 - Bad Request' 时修复 POST API 调用?

How to fix a POST API call when getting 'httpStatus 400 - Bad Request'?

我的目标是导出我使用 Google Apps 脚本在 Qualtrics 上进行的一项调查的回复。我试图让我的代码在 POST API 上工作,我得到了 ping 代码,但是无论它在 ping 什么,它都会返回一个 'httpStatus: 400-Bad request' 错误。

我对 Google Apps 脚本和使用 API 都是新手,但了解它的要点。我使用 Postman 获取了 javaScript Jquery ajax 代码并使其与 GAS 一起使用。令我困惑的是,当我将相同的代码与 GET APIs 一起使用并手动输入 ID(使用 POSTMAN 给我)时,它会完美地执行 ping 操作。当 运行 通过 Postman 时,它表明一切正常,所以不确定我在 POST 调用中做错了什么。

var option = {
  async: true,
  crossDomain: true,
  //url:"https://ousurvey.ca1.qualtrics.com/API/v3/surveys/SV_8dK8AKUFyAH8qyN//export-responses/",
  method: "POST",
  "headers": {
    "X-API-TOKEN": "**************************",
    "Content-Type": "application/json",
    "cache-control": "no-cache",
    "Postman-Token": "7a148b75-fa03-4f45-9782-08791c2f1c35"
  },
  processData: false,
  data : '{"format": "csv}',
  muteHttpExceptions: true //muted to check Logger
   };
 var qUrl='https://ousurvey.ca1.qualtrics.com/API/v3/surveys/SV_8dK8AKUFyAH8qyN/export-responses/'
 var getSurvey = UrlFetchApp.fetch(qUrl, option);

我需要让 POST 工作以获取 JSON 以获得调查 ID,这样我就可以使用该 ID 和 GET API 将信息下载到 google 驱动并将信息转换成 GoogleDocs.

这是日志中的当前错误:

{"meta":{"httpStatus":"400 - Bad Request","error":{"errorMessage":"Error decoding json body:
 com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input\n at 
[Source: akka.util.ByteIterator$ByteArrayIterator$$anon@71f9c2bb; line: 1, column: 0]"}}}

将 "Content-Type" 更改为 "contentType" 后出现此错误:

""meta":{"requestId":"62b3a313-b1ba-4939-83b7-ee73e65b4e3e","httpStatus":"400
 - Bad Request","error":{"errorCode":"QVAL_1","errorMessage":"Json type request body is expected.""

从你的问题和回复的评论来看,我大概理解了上面的意思。当我看到你提供的文档时,我发现示例 curl 命令如下。

curl -X POST \
-H 'X-API-TOKEN: yourapitokenhere' \
-H 'Content-Type: application/json' \
-d '{"format": "csv"}' \
'https://yourdatacenterid.qualtrics.com/API/v3/surveys/SV_012345678912345/export-responses'

我将此示例转换为 Google Apps 脚本的脚本。示例脚本如下

示例脚本:

var qUrl = "https://ousurvey.ca1.qualtrics.com/API/v3/surveys/SV_8dK8AKUFyAH8qyN/export-responses/";
var option = {
  method: "post",
  headers: {"X-API-TOKEN": "###"},
  contentType: "application/json",
  payload: JSON.stringify({"format": "csv"}),
  muteHttpExceptions: true,
};
var getSurvey = UrlFetchApp.fetch(qUrl, option);
Logger.log(getSurvey)

注:

  • 以上示例脚本与示例 curl 命令的请求相同。但是如果你运行脚本出现错误,请确认X-API-TOKEN、URL等参数的值是否符合你的情况。

参考文献: