分享方式:


從 Web 擷取資源

如果您需要管理 Web 上的資源,請使用下列 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 不正確的要求) ,服務就會停止處理您的腳本,並將錯誤訊息寫入記錄檔。 訊息包含要求的 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 物件,所以範例會將 參數設定 contentTypeapplication/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 腳本。

  1. 移至 https://apps.dev.microsoft.com ,然後按一下 [新增應用程式]
  2. 輸入應用程式名稱,例如 腳本用戶端。 (請勿檢查引導式 setup.)
  3. 按一下 [建立 ],並記下您的應用程式識別碼 (用戶端識別碼) 。
  4. 依序按一下 [新增平臺 ] 和 [ 原生應用程式]
  5. [Microsoft Graph 委派的許可權] 底下,按一下 [ 新增 ],然後選取 [檔案][.讀取並offline_access]。
  6. 按一下儲存

開啟記事本或您最愛的編輯器,並將 PowerShell 腳本複製到編輯器。 將 設定 $clientID 為您在註冊應用程式時收到的應用程式識別碼。

$clientId = "abc123-4d9e-44f1-837d-a7244af50027"

儲存檔案並將它命名 GetTokens.ps1 (您可以為它命名任何您想要的專案,但副檔名必須 .ps1) 。

現在開啟主控台視窗。 若要在 Microsoft Windows 上開啟主控台視窗,請輸入下列 Windows Run 命令 (< Windows button > +r) :

cmd.exe

在命令提示字元中,流覽至您儲存 GetTokens.ps1 的資料夾。 然後,輸入下列命令。

powershell.exe -File .\GetTokens.ps1

如果您收到執行原則錯誤,則必須變更執行原則。 如需執行原則選項,請 參閱關於執行原則。 若要變更會話的執行原則,請輸入下列命令:

powershell.exe -ExecutionPolicy Bypass -File .\GetTokens.ps1

當 PowerShell 腳本成功執行時,它會啟動瀏覽器會話,您會在其中輸入您的 Microsoft 帳戶 (MSA) 認證 (認證必須能夠存取您的 OneDrive 檔案) 。 同意之後,瀏覽器的網址列會包含授與碼 (請參閱 ?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 檔案的範例

取得重新整理權杖之後,下列範例示範如何) 使用重新整理權杖來取得存取權杖,而 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 服務