Google脚本中的google qpx查询

时间:2015-02-23 12:30:23

标签: google-apps-script

我试图通过Apps脚本通过谷歌航班服务请求(简单)航班查询

这是我的代码

    function myFunction() {
    var api_key = "XXXXXXXXXXXXXXX";
    var url2= "https://www.googleapis.com/qpxExpress/v1/trips/search?key=" + api_key;
    var param2 ={
      "method" : "POST",
      "contentType":"application/json",
      "headers" : {"Content-Type": "application/json"
     },
      "request": {"passengers": {"adultCount": 1},
      "slice": [{"origin": "BOS","destination": "LAX","date": "2015-03-01"}]
      },
       muteHttpExceptions : true
    }; 
    try {
    var response = UrlFetchApp.fetch(url2,param2);  
      Logger.log(response)
      } catch (e) {
        Logger.log(e)
      }
    }

此请求发送错误代码

"error": {"errors": [{
    "domain": "global",
    "reason": "badRequest",
    "message": "Invalid inputs: received empty request."
   }
  ],
  "code": 400,
  "message": "Invalid inputs: received empty request."
 }

qpx Api在我的开发者控制台中加载....任何人都有任何想法?

提前致谢

2 个答案:

答案 0 :(得分:0)

两件事,请求的主体必须用"有效载荷"来指定。属性,而不是"请求",您必须在发布之前将Javascript对象实际转换为JSON字符串。 (你也不需要"标题"属性," contentType"就足够了,但我认为它不会伤害任何东西)

var param2 ={
  "method" : "post",
  "contentType":"application/json",
  "payload": JSON.stringify({"passengers": {"adultCount": 1},
                             "slice": [{"origin": "BOS",
                                        "destination": "LAX",
                                        "date": "2015-03-01"
                                      }]
                             }
                           ),
   muteHttpExceptions : true
}; 

这里记录了所有内容:https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)

但是,JSON.stringify()的需要通常会引发人们的注意,如果你直接在有效负载中传递Javascript对象,它将作为表单编码的键/值对发布。

答案 1 :(得分:0)

非常感谢...你让我朝着正确的方向前进!  这是正确的语法:

var param2 ={
  "method" : "post",
  "contentType":"application/json",
  "payload": JSON.stringify
              (
              {"request":
                             {"passengers": {"adultCount": 1},
                             "slice": [{"origin": "BOS",
                                        "destination": "LAX",
                                        "date": "2015-03-01"
                                      }]
                             }
              }
              ),
   muteHttpExceptions : true
};