我是使用API连接使用Google脚本将数据输入Google Sheets的新手。
我如何写CURL请求下面在谷歌脚本?
curl -u {client_id}:{client_secret}
https://api.podbean.com/v1/oauth/token
-X POST -d 'grant_type=authorization_code&code={code}&redirect_uri={your_redirect_uri}'
这个
curl https://api.podbean.com/v1/analytics/podcastReports
-G -d 'access_token={access_token}' -d 'podcast_id={podcast_id}' -d 'year=2018'
我相信你的目标如下。
-
您想要将以下2个curl命令转换为Google Apps Script。
-
Curl命令1.
curl -u {client_id}:{client_secret} https://api.podbean.com/v1/oauth/token -X POST -d 'grant_type=authorization_code&code={code}&redirect_uri={your_redirect_uri}'
-
Curl命令2.
curl https://api.podbean.com/v1/analytics/podcastReports -G -d 'access_token={access_token}' -d 'podcast_id={podcast_id}' -d 'year=2018'
-
Curl命令1示例脚本:
function sample1() {
// Please set your values to the following variables.
const client_id = "your client_id";
const client_secret = "your client_secret";
const code = "your code";
const redirect_uri = "your redirect_uri";
const params = {
method: "post",
payload: {
grant_type: "authorization_code",
code: code,
redirect_uri: redirect_uri
},
headers: {Authorization: "Basic " + Utilities.base64Encode(`${client_id}:${client_secret}`)},
muteHttpExceptions: true
};
const url = "https://api.podbean.com/v1/oauth/token";
const res = UrlFetchApp.fetch(url, params);
console.log(res.getContentText())
}
Curl命令2的示例脚本:
function sample2() {
// Please set your values to the following variables.
const access_token = "your access_token";
const podcast_id = "your podcast_id";
const year = "2018";
const baseUrl = "https://api.podbean.com/v1/analytics/podcastReports";
const url = `${baseUrl}?access_token=${access_token}&podcast_id=${podcast_id}&year=${year}`;
const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
console.log(res.getContentText())
}
注意:
在使用上述脚本之前,请再次确认脚本中
client_id
,client_secret
,code
,redirect_uri
,access_token
,podcast_id
,year
的值关于"Curl命令2示例脚本",当
access_token
和podcast_id
的值中包含特殊字符时,请对const url = `${baseUrl}?access_token=${encodeURIComponent(access_token)}&podcast_id=${encodeURIComponent(podcast_id)}&year=${year}`;
等值使用encodeURIComponent()
。 参考: