如何在get方法中使用post方法中的getResponseHeader?

时间:2016-08-25 19:33:18

标签: javascript httprequest titanium-alloy getresponse skyscanner

我正在与SkyScanner API合作,按航班详细信息获取实时价格。

正如文件所说。我创建了实时定价服务会话。可以通过对api的post请求创建,然后通过使用此SessionKey和apiKey提供SessionKey我可以重新获取数据。我可以使用在success方法中使用的getResponseHeader(" Location")来查看sessionKey。然后我将它提交给一个全局变量urlSession,我稍后在另一个http get请求中使用它作为url。 我可以在警报中看到SessionKey,但是当我尝试在get方法中使用它时,我有一个未定义的错误。我不确定它是CORS问题还是语法。

var hrpost = Ti.Network.createHTTPClient();
// post_params
  var post_params = {
      "apiKey" : {apiKey},
       "Country" : "US",
    "Currency" : "USD",
    "Locale" : "en-GB",
    "Adults" : 1,
    "Children" : 0,
    "Infants" : 0,
    "OriginPlace" : "16216",
    "DestinationPlace" : "1111",
    "OutboundDate" : "2016-09-23",
    "InboundDate" : "2016-09-30",
    "LocationSchema" : "Default",
    "CabinClass" : "Economy",
    "GroupPricing" : true

  };
  var strMyObj = JSON.stringify(post_params);
  //Here I set the webservice address and method
hrpost.open('POST', "http://partners.api.skyscanner.net/apiservices/pricing/v1.0");
 //Set the headers
  hrpost.setRequestHeader("Accept", "application/json");
hrpost.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
hrpost.send(post_params);

hrpost.onload = function(){

    alert('Posted successfully');
    urlsessionKey = hrpost.getResponseHeader('Location');
    alert(urlsessionKey);

}
 hrpost.onerror = function() {
alert('request didnt posted');
var rejection = {
            status: hrpost.status,
            statusText: hrpost.statusText,


        };
        alert(rejection);
};



//HTTP request get method to send the sessionKey and retrieve data
var xmlHttp = Ti.Network.createHTTPClient();



 var post_params = {
      "apiKey" : {apiKey},
       "Country" : "US",
    "Currency" : "USD",
    "Locale" : "en-GB",
    "Adults" : 1,
    "Children" : 0,
    "Infants" : 0,
    "OriginPlace" : "16216",
    "DestinationPlace" : "1111",
    "OutboundDate" : "2016-09-23",
    "InboundDate" : "2016-09-30",
    "LocationSchema" : "Default",
    "CabinClass" : "Economy",
    "GroupPricing" : true

  };
//here the error occurs when I use the sessionKey I stored in the global var urlsessionKey  
xmlHttp.open('GET', urlsessionKey);

   xmlHttp.setRequestHeader("Accept", "application/json");
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");


xmlHttp.send(post_params);

xmlHttp.onload = function(e){

     alert('Get successfully');
}
 xmlHttp.onerror = function() {
 alert('request didnt posted');
 var rejection = {
            status: xmlHttp.status,
            statusText: xmlHttp.statusText,

        };
        alert(rejection);
};

1 个答案:

答案 0 :(得分:0)

我认为错误可能是因为您在文档中轮询会话时没有使用api键进行调用says。试试这样:

   var urlsessionKey = hrpost.getResponseHeader('Location') + "?apiKey=" + {apiKey};

无论如何,在FAQ of Skyscanner中,航班直播定价服务不允许使用CORS版本,因此您可能必须从服务器端执行此调用。我几天前发布了第一次通话的example in Java,如果它对你有帮助的话。

希望它有所帮助!