google apps script ==> UrlFetchApp, method GET and cookie

ε祈祈猫儿з 提交于 2019-12-10 19:59:14

问题


I use the UrlFetchApp to send the user and pwd (method POST). After get the cookie, and use in other request (method GET). But this new request not working, I think that this cookie not has correct use in this new request. Can anyone help me?

  var opt ={
    "method":"post",
    "User-Agent" : "Mozilla/5.0",
    "Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language" : "en-US,en;q=0.5",    
    "payload": this.payload.toString(), 
    "followRedirects" : false
  };
  var response = UrlFetchApp.fetch("https://edas.info/addTopic.php?c=19349",opt);
  var resp1=response.getContentText();    
  Logger.log(resp1);  
  response.getResponseCode();

  var headers = response.getAllHeaders();
  var cookies = headers['Set-Cookie']; 
  for (var i = 0; i < cookies.length; i++) {
    cookies[i] = cookies[i].split( ';' )[0];
  };


  opt = {
    "method" : "get",
    "User-Agent" : "Mozilla/5.0",
    "Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language" : "en-US,en;q=0.5",    
    "headers": {
      "Cookie": cookies.join(';')
    },
    "followRedirects" : false    
  };
  response = UrlFetchApp.fetch("https://edas.info/addTopic.php?c=19349", opt);
  var resp1=response.getContentText();  
  Logger.log(resp1);  

回答1:


First off, thanks you for the snippet of code, this got me started with processing cookies in such script. I encountered an issue that was possibly your problem. Sometimes a Web page returns an array of cookies, and then your code works fine. Sometimes it returns a single string (instead of an array of one string). So I had to disambiguate with a test like:

if ( (cookies != null) && (cookies[0].length == 1) ) {
      cookies = new Array(1);              
      cookies[0] = headers['Set-Cookie']; 
}



回答2:


I cannot give you specific help for your problem, one pointer though, as found here Cookie handling in Google Apps Script - How to send cookies in header?

As https://stackoverflow.com/users/1435550/thierry-chevillard put it:

Be aware also that GAS uses Google IPs. It can happen that two consecutive fetch use different IPs. The server your are connecting to may be session-IP dependant.

Does your code run on the local development server and only fail once deployed to App Engine? Or does it fail locally, as well?



来源:https://stackoverflow.com/questions/27474674/google-apps-script-urlfetchapp-method-get-and-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!