【问题标题】:UrlFetchApp returns error 404UrlFetchApp 返回错误 404
【发布时间】:2016-12-07 05:06:39
【问题描述】:

我尝试使用 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());

  }

【问题讨论】:

    标签: google-apps-script


    【解决方案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());
    }
    

    【讨论】:

    • 工作完美。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2016-04-07
    • 2014-01-26
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多