我有一段PHP代码需要转换为Google Script。代码从服务器(URL)获取JSON数据,并使用Digest auth(RFC 2617)方法验证访问数据的凭据。我没有成功地让Google脚本使用 UrlFetchApp.fetch(url,opt)行返回401错误(访问被拒绝)。我想这与我如何通过Google中的用户/密码参数有关。
供参考,这就是可用的PHP脚本:
<?php
$url = "https://myurl.com/status.php"; // API URL
$user = "ABCDE"; // user credential
$pass = "mypass"; // password credential
$fields = array(
"device" => 4,
"from" => "2010-08-22",
"to" => "2010-08-24"
) ;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_USERPWD, "$user:$pass");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch); // send the request
curl_close($ch);
print_r (json_decode($result)); // process the response
?>
以下是Google Script代码:
function getStatus() {
var opt = {
serial: "ABCDE",
pass : "mypass"
};
var url = "https://myurl.com/status.php";
var response = UrlFetchApp.fetch(url, opt);
}
更新:以下是我收到401错误的脚本:
// https://user:pass@url.com/api/status.php?
//
function getstatus() {
var opt = {};
opt.headers = {"serial": "pass " + Utilities.base64Encode("ABCD" + ":" +
"123-AAA")};
var url = "https://url.com/api/status.php";
var response = UrlFetchApp.fetch(url, opt);
}