google apps脚本==> UrlFetchApp,方法GET和Cookie [英] google apps script ==> UrlFetchApp, method GET and cookie
问题描述
我使用UrlFetchApp发送用户和pwd(方法POST)。获得cookie后,并在其他请求(方法GET)中使用。但是这个新请求不起作用,我认为这个cookie在这个新请求中没有正确使用。有人可以帮我吗?
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);
推荐答案
首先,谢谢您的代码片段,这使我开始使用这种脚本处理Cookie。我遇到了可能是您的问题的问题。有时网页返回一个cookie数组,然后您的代码可以正常工作。有时它返回一个字符串(而不是一个字符串的数组)。因此,我不得不消除以下测试的歧义:
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'];
}
这篇关于google apps脚本==> UrlFetchApp,方法GET和Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!