I have a working piece of PHP code that I need to convert to Google Script. The code fetches JSON data from a server (URL) and uses Digest auth (RFC 2617) method to validate credentials for accessing data. I have not been succesful in getting the Google script to work with the UrlFetchApp.fetch(url, opt) line that returns a 401 error (access denied). I guess it has to do on how I pass the user/password paramters in Google.
For reference, this is what the working PHP script looks like:
<?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
?>
Here is the Google Script code:
function getStatus() {
var opt = {
serial: "ABCDE",
pass : "mypass"
};
var url = "https://myurl.com/status.php";
var response = UrlFetchApp.fetch(url, opt);
}
UPDATE: Here is the script that I am getting the 401 errors for:
// 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);
}