7

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);  
Nijin Narayanan
  • 2,269
  • 2
  • 27
  • 46
user14272
  • 87
  • 1
  • 1
  • 5

2 Answers2

4

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']; 
}
siamond
  • 41
  • 2
0

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?

Community
  • 1
  • 1
Related
  • 1
  • 1
  • I have same code and request on local python project(it works). But Failed in the GAS. Couldn't figure out why – liquidkat May 03 '22 at 17:49