title: Cookie handling in Google Apps Script - How to send cookies in header?
body: <p>I'm trying to write a simple script that fetches text from a webpage and processes that string. But, that website requires me to be logged in. I was successful in logging in to that website. This is how I logged in:</p>
  
  <pre><code>var payload = {"name1":"val1","name2":val2"};
  
  var opt ={"payload":payload,"method":"post"};
  
  var respose = UrlFetchApp.fetch("http://website.com/login",opt);
  </code></pre>
  
  <p>After logging in, the website places me in <code>http://website.com/home</code>. I checked <code>response.getContentText()</code> and I can confirm that I have been logged in successfully as it contains the text from <code>http://website.com/home</code>.
  Now I need to get the contents of <code>http://website.com/page</code> and process it.
  I first assumed the script can handle cookies by itself and proceeded with </p>
  
  <pre><code>var pagedata = UrlFetchApp.fetch("http://website.com/page);//Did not work
  </code></pre>
  
  <p>That obviously didnt work and <code>pagedata.getContentText()</code> says me to login first, which indicates cookies were not successfully passed..</p>
  
  <p>I then tried to extract cookies which the server responded during login and to send it along with this request.</p>
  
  <pre><code>var cookie = response.getAllHeaders()['Set-Cookie'];     
  
  // variable cookie now contains  a legitimate cookie.
  
  // It contains 'JSESSIONID=blabla;Path=/' and 
  // it is the ONLY cookie that server responds.
  </code></pre>
  
  <p>I tried to send that cookie in my page request.</p>
  
  <pre><code>var header = {'Cookie':cookie};
  
  var opt2 = {"header":header};
  
  var pagedata = UrlFetchApp.fetch("http://website.com/page",opt2);
  </code></pre>
  
  <p>I think even now cookies were not properly sent, as the content again says me to login.</p>
  
  <p>Am I passing cookies correctly? I need help regarding the correct method of sending cookies in a request.</p>