谷歌脚本上的"需要身份验证"消息



所以我尝试使用API使用Google Script提取一些数据。

API文档告诉我这样做:

要进行身份验证:

POST /safefleet/api/authenticate HTTP/1.1
Host: api.safefleet.eu
Content-Type: application/json
{"username": "test", "password": "1234"}

然后我得到了这个回应,这是可以的,因为我得到了:

HTTP/1.1 200 OK
Content-Type: application/json
Set-Cookie: sessionid=4ce508d20832d12a64fd49ecb336a7b6
{"message": "ok"}

之后,我想得到我需要的数据,它告诉我这样做:

GET /safefleet/api/vehicles HTTP/1.1
Host: api.safefleet.eu
Cookie: sessionid=4ce508d20832d12a64fd49ecb336a7b6

我应该得到的答案应该是这样的:

HTTP/1.1 200 OK
Content-Type: application/json
[
{"vehicle_id": 1234, "name": "Vehicle A", ...},
{"vehicle_id": 2345, "name": "Vehicle B", ...}
...
]

但我得到的却是"需要身份验证"。。。

这是代码:

function Vehicles() {

var LogIn = UrlFetchApp.fetch("https://alpha.safefleet.eu/safefleet/api/authenticate/?username=test&password=123");
Logger.log(LogIn.getHeaders()["Set-Cookie"]);
var s = LogIn.getHeaders()["Set-Cookie"];
var sessionid = JSON.stringify(s);
var cookie = {
"Cookie" : sessionid
};
var headers = {
"Cookie": cookie
};
var params = {
"method": "GET",
"muteHttpExceptions": true,
"headers": headers
};
var Vehicles = UrlFetchApp.fetch("https://alpha.safefleet.eu/safefleet/api/vehicles/", params);
Logger.log(Vehicles);
}

试着看看这是否有效。

function Vehicles() {
var payload = {
"username": "test",
"password": "123"
};
var options = {
'method' : 'post',
'muteHttpExceptions': true,
'payload' : payload
};
var LogIn = UrlFetchApp.fetch("https://alpha.safefleet.eu/safefleet/api/authenticate", options);
var cookie = LogIn.getHeaders()["Set-Cookie"];
var headers = {
"Cookie": cookie
};
var params = {
"method": "GET",
"muteHttpExceptions": true,
"headers": headers
};
var Vehicles = UrlFetchApp.fetch("https://alpha.safefleet.eu/safefleet/api/vehicles/", params);
Logger.log(Vehicles);
}

相关内容

最新更新