訓練
模組
Access REST services from within Dynamics 365 Business Central - Training
Learn how to use HTTP data types, connect to external REST services, and handle JSON data in Dynamics 365 Business Central.
本主題包含如何撰寫腳本,透過 Microsoft Windows HTTP 服務 (WinHTTP) 同步或非同步取得資料的腳本。 此範例中示範的概念提供撰寫需要使用 HTTP 通訊協定存取資料的用戶端或仲介層伺服器應用程式的基礎。
除了 Microsoft JScript 的工作知識之外,此範例還需要下列各項:
若要建立以同步方式從網頁取得文字的腳本,請執行下列動作:
開啟文字編輯器。
將下列程式碼複製到文字編輯器中。
function getText(strURL)
{
var strResult;
try
{
// Create the WinHTTPRequest ActiveX Object.
var WinHttpReq = new ActiveXObject(
"WinHttp.WinHttpRequest.5.1");
// Create an HTTP request.
var temp = WinHttpReq.Open("GET", strURL, false);
// Send the HTTP request.
WinHttpReq.Send();
// Retrieve the response text.
strResult = WinHttpReq.ResponseText;
}
catch (objError)
{
strResult = objError + "\n"
strResult += "WinHTTP returned error: " +
(objError.number & 0xFFFF).toString() + "\n\n";
strResult += objError.description;
}
// Return the response text.
return strResult;
}
WScript.Echo(getText("https://www.microsoft.com/default.htm"));
將檔案儲存為 「Retrieve.js」。
在命令提示字元中,輸入 「cscript Retrieve.js」,然後按 ENTER 鍵。
您現在有使用 WinHttpRequest 物件的腳本,以取得網頁 https://www.microsoft.com 的 HTML 原始程式碼。 您可能必須等候數秒,程式碼才會出現。
應用程式只包含一個函式 「getText」。 腳本的第一行會建立 WinHttpRequest 物件。
// Create the WinHTTPRequest ActiveX Object.
var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
當 JScript 引擎遇到這一行時,它會建立這個物件的實例。 如果您收到錯誤訊息:「ActiveX 元件無法建立物件」,則在此行上,最有可能是WinHttp.dll未正確註冊或不存在於系統上。
腳本的下一行會呼叫 Open 方法。
// Create an HTTP request.
WinHttpReq.Open("GET", "https://www.microsoft.com", false);
三個參數會指定要使用的 HTTP 動詞動詞 、資源的名稱,以及是否以同步或非同步方式使用 WinHTTP。 在此範例中,方法使用 HTTP 動詞「GET」 從 https://www.microsoft.com 取得資料。 為最後一個參數指定 FALSE 會決定交易會同步發生。 Open方法不會建立與資源的連線,因為名稱可能表示。 相反地,它會初始化內部資料結構,以維護會話、連線和要求的相關資訊。
Send方法會組合要求標頭,並傳送要求。 在同步模式中呼叫時, Send 方法也會等候回應,再允許應用程式繼續。
// Send the HTTP request.
WinHttpReq.Send();
傳送要求之後,腳本會傳回WinHttpRequest物件的ResponseText屬性值。 此屬性包含回應的實體本文,在此案例中為檔的來源。
// Get the response text.
return WinHttpReq.ResponseText;
擷取資源的整個文字時,腳本的執行會暫停。 資源文字會從 函式傳回並顯示。
WinHttpRequest物件可確保已配置給 HTTP 交易的任何內部資源都已釋放。
使用 WinHTTP 以非同步方式擷取資料與同步擷取資料非常類似。 藉由進行兩個小型變更,修改上一節中的腳本。
將 Open 方法的第三個參數設定為 「true」,而不是 「false」,以指定應該以非同步方式執行 WinHTTP 方法。
// Create a HTTP request.
var temp = WinHttpReq.Open("GET", strURL, true);
先叫用 WaitForResponse 方法,再存取 ResponseText 屬性,以確保已收到整個回應。
// Send the HTTP request.
WinHttpReq.Send();
// Wait for the entire response.
WinHttpReq.WaitForResponse();
// Retrieve the response text.
strResult = WinHttpReq.ResponseText;
在腳本中以非同步方式使用 WinHTTP 的主要優點是 Send 方法會立即傳回。 要求是由背景工作執行緒準備並傳送。 這可讓您的應用程式在等候回應時執行其他動作。 嘗試存取回應之前,請先呼叫 WaitForResponse 方法,確定已收到整個回應。 否則會發生錯誤。
WaitForResponse方法也可用來指定交易的逾時值。 選擇性參數可讓您以秒為單位指定逾時值。
訓練
模組
Access REST services from within Dynamics 365 Business Central - Training
Learn how to use HTTP data types, connect to external REST services, and handle JSON data in Dynamics 365 Business Central.