如果您需要管理網路上的資源,請使用下列方法的 UrlFetchApp。
簡易 GET 要求
如果您只需要取得 Web 資源,請使用 fetch(url) 。
var response = UrlFetchApp.fetch('https://www.contoso.com');
fetch(url)此方法會傳回 HTTResponse 物件,其中包含用於讀取回應的方法。 使用 getContentText 讀取文字回應及 getContent 讀取二進位回應的方法。
如果回應內文包含 JSON 物件,請使用 來 getContentText 取得 JSON 物件。 若要存取 JSON 物件中的個別欄位,請使用 JSON.parse() 方法來剖析回應。
var stock = JSON.parse(response.getContentText());
Logger.log(`stock symbol: ${stock["symbol"]}`);
Logger.log(`company: ${stock["companyName"]}`);
Logger.log(`close price: ${stock["close"]}`);
處理 HTTP 錯誤
如果要求失敗 (例如,400 Bad request) ,服務會停止處理您的指令碼,並將錯誤訊息寫入記錄檔。 該訊息包含要求的 HTTP 狀態代碼,但不包含回應本文中可能存在的錯誤訊息。
如果您需要取得回應主體,請改為呼叫 fetch(url, params) 方法,並將 muteHttpExceptions 參數設定為 true。 將 muteHttpExceptions 設定為 true 一律會傳回指令碼的控制權。 接著,您需要呼叫 getResponseCode() 該方法來確定請求的成功或失敗並採取相應的行動。
var response = UrlFetchApp.fetch('https://contoso.com', { muteHttpExceptions: true });
if (200 == response.getResponseCode())
{
Logger.log('HTTP request succeeded');
}
else
{
Logger.log('HTTP request failed');
}
新增、更新或刪除 Web 資源
如果您需要新增、更新或刪除 Web 資源,請使用 擷取 (URL、參數) 方法。 此方法可讓您指定要使用的 HTTP 動詞、Content-Type 標頭、要求所需的任何其他標頭,以及要求的承載。 如需這些參數的詳細資訊,請參閱 UrlFetchParams 物件。
下列範例會取得需要 OAuth 存取權杖的資源。 因為 GET 是擷取方法的預設 HTTP 動詞,所以您需要指定的唯一參數就是 headers 參數。
var token = "<the oauth token goes here>";
var response = UrlFetchApp.fetch('https://contoso.com', { headers: { Authorization: `Bearer ${token}` } });
var jsonObject = JSON.parse(response.getContentText());
此範例會傳送包含 JSON 承載的 POST 要求。 由於承載是 JSON 物件,因此範例會將 contentType 參數設定為 application/json。
var myData = {
'id' : '123abc',
'name' : 'leg',
'color' : 'red'
};
var options = {
'method' : 'post',
'contentType' : 'application/json',
'payload' : JSON.stringify(myData)
};
var response = UrlFetchApp.fetch('https://contoso.com', options);
var jsonObject = JSON.parse(response.getContentText());
使用 UrlFetchApp 從 OneDrive 取得資料檔案或 CSV 檔案。
若要從 OneDrive (https://onedrive.live.com) 取得檔案,請使用 Microsoft Graph。 存取 OneDrive 檔案需要 OAuth 存取權杖。 除非您有重新整理權杖,否則取得存取權杖需要使用者同意。 但由於指令碼不支援 UI 元件,因此您需要以其他方式取得同意。 如果您還沒有其他取得重新整理權杖的方法,您可以執行以下 PowerShell 指令碼來取得同意和重新整理權杖。
$clientId = "your application ID goes here"
Start-Process "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=$clientId&scope=files.read offline_access&response_type=code&redirect_uri=https://login.live.com/oauth20_desktop.srf"
$code = Read-Host "Please enter the code"
$response = Invoke-WebRequest https://login.microsoftonline.com/common/oauth2/v2.0/token -ContentType application/x-www-form-urlencoded -Method POST -Body "client_id=$clientid&redirect_uri=https://login.live.com/oauth20_desktop.srf&code=$code&grant_type=authorization_code"
Write-Output "Refresh token: " ($response.Content | ConvertFrom-Json).refresh_token
您必須先依照下列步驟取得用戶端識別碼,才能執行 PowerShell 指令碼。
- 移至 https://apps.dev.microsoft.com 並按一下 [新增應用程式]。
- 輸入應用程式名稱,例如 Scripts 用戶端。 (請勿選取 [引導式設定].)
- 按一下 [建立] ,並記下您的應用程式識別碼 (用戶端識別碼) 。
- 按一下 [新增平台 ],然後按一下 [原生應用程式]。
- 在 [Microsoft Graph 委派的權限] 底下,按一下 [新增],然後選取 [Files]。閱讀並offline_access。
- 按一下儲存。
開啟記事本或您最愛的編輯器,然後將 PowerShell 指令碼複製到編輯器。 設定 $clientID 為您註冊應用程式時收到的應用程式識別碼。
$clientId = "abc123-4d9e-44f1-837d-a7244af50027"
儲存檔案並將其命名 GetTokens.ps1 (您可以任意命名,但副檔名必須 .ps1) 。
現在,請開啟主機視窗。 若要在 Microsoft Windows 上開啟主控台視窗,請輸入下列 Windows 執行命令 (<Windows button>+r) :
cmd.exe
在命令提示字元中,瀏覽至您儲存 GetTokens.ps1 的資料夾。 然後,輸入下列命令。
powershell.exe -File .\GetTokens.ps1
如果收到執行原則錯誤,則必須變更執行原則。 如需執行原則選項,請參閱 關於執行原則。 若要變更工作階段的執行原則,請輸入下列命令:
powershell.exe -ExecutionPolicy Bypass -File .\GetTokens.ps1
當 PowerShell 指令碼成功執行時,它會啟動瀏覽器工作階段,您可以在其中輸入 Microsoft 帳戶 (MSA) 認證 (認證必須有權存取您的 OneDrive 檔案) 。 同意之後,瀏覽器的網址列會包含授權代碼 (請參閱 ?code={copy this code}) 。
https://login.live.com/oauth20_desktop.srf?code=M7ab570e5-a1c0-32e5-a946-e4490c822954&lc=1033
複製授與碼 (M7ab570e5-a1c0-32e5-a946-e4490c822954) ,然後在主控台視窗中輸入提示。 PowerShell 指令碼接著會傳回重新整理權杖。 在指令碼中使用重新整理權杖來取得存取權杖。 您應該像對待密碼一樣對待重新整理權杖;如果有人掌握了它,他們便可以存取您的 OneDrive 資料。
重新整理權杖存留時間很長,但可能會變成無效。 如果您收到invalid_grant錯誤,您的重新整理權杖將不再有效,您必須再次執行 PowerShell 指令碼以取得同意和新的重新整理權杖。
下載 CSV 檔案的範例
取得重新整理權杖之後,下列範例示範如何 1) 使用重新整理權杖取得存取權杖,以及 2) 呼叫 Microsoft Graph 以取得用來下載 CSV 檔案的下載 URL。 將 {yourclientid} 取代為您已註冊應用程式的應用程式識別碼,並將 {yourrefreshtoken} 取代為您的重新整理權杖。
function main() {
var clientId = "{yourclientid}";
var refreshToken = "{yourrefreshtoken}";
var options = {
'method' : 'post',
'contentType' : 'application/x-www-form-urlencoded',
'payload' : `client_id=${clientId}&redirect_uri=https://login.live.com/oauth20_desktop.srf&refresh_token=${refreshToken}&grant_type=refresh_token`
};
// Use the refresh token to get the access token.
var response = UrlFetchApp.fetch('https://login.microsoftonline.com/common/oauth2/v2.0/token', options);
var tokens = JSON.parse(response.getContentText());
// Get the contents of the CSV file from OneDrive passing the access token in the Authorization header.
// Replace the path and file name (/me/drive/root/children/bids.csv) with your path and file name.
response = UrlFetchApp.fetch('https://graph.microsoft.com/v1.0/me/drive/root/children/bids.csv/content', { headers: { Authorization: `Bearer ${tokens['access_token']}` } });
// Read and parse the contents of the file. The parseCSV method is a placeholder for
// whichever method you provide to parse the file.
var file = response.getContentText();
var data = parseCSV(file);
}
剖析 CSV 檔案
沒有內建的 CSV 剖析工具,因此您必須自己撰寫或在線上尋找工具。 例如,在線上快速搜尋可在 Stack Overflow 上找到 這個 。 如果您在網上找到一個,請確保它沒有使用限制。
存取 Google 服務
如需使用 UrlFetchApp 存取 Google 服務的詳細資訊,請參閱 呼叫 Google 服務。