UrlFetchApp返回错误404

时间:2016-12-06 20:27:06

标签: google-apps-script

我尝试使用UrlFetchApp从API获取信息。我在POSTMAN中尝试了GET和POST命令,它运行正常。在Google Apps脚本中,第一个有效,第二个返回错误404.

function pru_demo() {
// Log In.
var options = {
  'method' : 'POST',
  'contentType': 'application/json'
};
  var response=UrlFetchApp.fetch('https://demo.erpnext.com/api/method/login?usr=demo@erpnext.com&pwd=demo', options);
  var data=JSON.parse(response)
  Logger.log(data.full_name);

// Get Employes
options = {
//  'muteHttpExceptions' : true,
  'method' : 'GET',
  'contentType': 'application/json'
};

response=UrlFetchApp.fetch('https://demo.erpnext.com/api/resource/Employee', options);
Logger.log(response.getContentText());

  }

1 个答案:

答案 0 :(得分:1)

当您发送初始登录请求时,服务器会返回用于会话的cookie。您需要提取这些cookie并在随后的所有请求中设置它们。

我修改了你的代码来证明这一点:

function pru_demo() {
  // Log In.
  var options = {
    'method' : 'POST',
    'contentType': 'application/json'
  };
  var response=UrlFetchApp.fetch('https://demo.erpnext.com/api/method/login?usr=demo@erpnext.com&pwd=demo', options);
  var data = JSON.parse(response)
  Logger.log(data.full_name);

  // Extract the cookies from the login response
  var cookies = response.getAllHeaders()['Set-Cookie'];
  var cookieParts = [];
  for (var i = 0; i < cookies.length; i++) {
    var arr = cookies[i].split('; ');
    cookieParts.push(arr[0]);
  }

  // Create a new cookie to send with subsequent requests
  var newCookie = cookieParts.join('; ');
  Logger.log(newCookie);

  // Get Employes
  options = {
  //  'muteHttpExceptions' : true,
    'method' : 'GET',
    'contentType': 'application/json',
    'headers': {
      'Cookie' : newCookie
    }
  };

  response = UrlFetchApp.fetch('https://demo.erpnext.com/api/resource/Employee', options);
  Logger.log(response.getContentText());
}