首页 > 解决方案 > 通过 urlfetchapp 发出请求会产生“异常:属性提供的值无效:标头:内容长度”

问题描述

目标是使用 urlfetchapp 和通过 Apps 脚本的 put 请求将订单的“OrderStatusID”更新为“1”。

function updateOrderStatus(){

  var private_key = "{private_key}";
  var merchant_token = "{merchant_token}";
  var secure_url = "{secure_url}";
  
  var body = JSON.stringify({"OrderStatusID": "1"});
  var url ="https://apirest.3dcart.com/3dCartWebAPI/v2/Orders/{orderID}";
  
  var options =  {
    "method" : "put",
    "headers" : {
      "Content-Type" : "application/json",
      "Content-Length" : body.length,
      "Accept" : 'application/json',
      "SecureURL" : secure_url,
      "PrivateKey" : private_key,
      "Token" : merchant_token
    },
    "body" : body,
    "muteHttpExceptions" : false,
  }
  try{
    var response = UrlFetchApp.fetch(url, options);
  }
  catch(err){
    Logger.log(err);
  }
  finally{
    Logger.log(response);
  }
}

代码抛出错误异常:属性提供了无效值:标题:内容长度

更改代码以删除敏感信息。

标签: exceptiongoogle-apps-scripturlfetch

解决方案


将选项“body”的名称更改为“payload”解决了这个问题。

在这个谷歌问题跟踪线程中找到了答案。

ek...@googlers.comek...@googlers.com #6Apr 11, 2016 07:03AM 状态:无法修复(不可重现) UrlFetchApp 没有名为“contentLength”的高级参数。Content-Length 标头是根据传入的有效负载的长度自动计算的。您在示例中设置的“contentLength”高级参数会被后端简单地忽略并自动计算长度。

Content-Length 是根据有效负载自动计算的。我认为它应该被命名为 body 因为3dCart API文档在示例中使用 body 作为其 json 的名称。

更正的代码:

function updateOrderStatus(){

  var private_key = "{private_key}";
  var merchant_token = "{merchant_token}";
  var secure_url = "{secure_url}";
  
  var body = JSON.stringify({"OrderStatusID": "1"});
  var url ="https://apirest.3dcart.com/3dCartWebAPI/v2/Orders/{orderID}";
  
  var options =  {
    "method" : "put",
    "headers" : {
      "Content-Type" : "application/json",
      //"Content-Length" : body.length,
      "Accept" : 'application/json',
      "SecureURL" : secure_url,
      "PrivateKey" : private_key,
      "Token" : merchant_token
    },
    "payload" : body,
    "muteHttpExceptions" : false,
  }
  try{
    var response = UrlFetchApp.fetch(url, options);
  }
  catch(err){
    Logger.log(err);
  }
  finally{
    Logger.log(response);
  }
}

推荐阅读