orchestrator
latest
false
UiPath logo, featuring letters U and I in white
Orchestrator 用户指南
Automation CloudAutomation Cloud Public SectorAutomation SuiteStandalone
Last updated 2024年11月4日

通话模式说明

API 触发器调用模式专门用于在 Orchestrator 中创建和跟踪作业执行。

基于 HTTP 的通信的根本挑战在于它本质上是同步的:通常,客户端会发送请求并等待来自服务器的响应。但是,在机器人作业的上下文中,Orchestrator 不支持在作业完成之前使连接保持打开。

为解决此问题,我们使用 HTTP 协议对多种调用模式进行建模。这些模式依赖于标准 HTTP 方法、状态代码和标头,以在系统中创建、监控和获取作业结果,而无需不必要地使连接保持打开。建议的每种调用模式都有各自的优缺点,因此您可以选择最适合自己的集成需求的模式。请记住,为确保安全通信,每次调用都需要通过持有者令牌进行适当的身份验证。

重要提示:

已知问题

有时可能会向请求返回 502 Bad Gateway Cloudflare 错误,这是由于大量连接在较长的时间间隔内保持活动状态所致。尽管出现错误,此类请求的基础作业可能已在运行,因此您可以在 Orchestrator 中检查其状态。

此问题是间歇性的,任何后续请求都将按预期运行。

异步轮询

此调用模式涉及使用预配置的 HTTP 谓词发出调用,以触发新作业并接收状态 URI。然后,必须手动轮询状态 URI,直到作业完成。此时,调用将重定向到另一个端点,该端点用于检索作业结果(输出或错误)。

异步轮询工作流,在此工作流中,作业的完成取决于对响应位置的中间手动调用

docs image

系统将使用已配置的 HTTP 谓词(GET、POST、PUT、DELETE)发出初始调用,这会在 Orchestrator 中创建关联的作业。成功创建作业后,系统将在 Location 标头中返回 HTTP 状态代码 202(已接受)和状态 URI 作为响应。

创建作业后,您应该定期轮询其状态。在此轮询过程中,只要作业正在运行,对状态 URI 的每个 GET 请求就会返回 HTTP 状态代码 200(正常)。作业完成后,对状态 URI 的下一个 GET 请求将返回 HTTP 状态代码 303(查看其他),并重定向到输出 URI(通过 Location 标头)。您应定向到输出 URI,以检索作业结果(输出或错误)。

始终确保在每次调用的标头中包含有效的持有者令牌,以便成功进行身份验证。

JavaScript 示例

此示例说明如何从浏览器中,通过 API 触发器使用“异步轮询”调用模式启动作业。

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

const url = 'https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>';
const token = '<PERSONAL_ACCESS_TOKEN>'; // could also be an access token retrieved via OAuth

const body = {
  'argument1': 123,
  'argument2': 'my string',
  '$callMode': 'AsyncRequestReply' // optional argument to force call mode to AsyncRequestReply
}

// if invocation is done by GET, place the parameters in query string and remove the 'Content-Type' header
const invokeRequestOptions = {
  method: 'POST',
  headers: new Headers({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }),
  body: JSON.stringify(body),
};

const redirectRequestOptions = {
  method: "GET",
  credentials: 'same-origin',
  headers: new Headers({ Authorization: `Bearer ${token}` }),
  redirect: "follow", // this option must be set to follow, otherwise an 'opaqueredirect' response is returned
};

const response = await fetch(url, invokeRequestOptions);
let newLocation = response.headers.get("Location");

// first response should be 202 and have a location header
console.log(`Got ${response.status}, with location: ${newLocation}`);

for (let i = 0; i < 20; i++) {
  await sleep(SLEEP_DURATION);

  // follow the location header to the new endpoint
  const statusResponse = await fetch(newLocation, redirectRequestOptions);

  // if the response was redirected (and automatically followed), then the output endpoint has been reached
  // the output of the job can be found in the body of the response in JSON format
  if (statusResponse.status != 200 || statusResponse.redirected)
  {
    // read the job output
    const output = await statusResponse.json();
    console.log(`Got ${statusResponse.status}, with body: ${JSON.stringify(output)}`);

    break;
}const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

const url = 'https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>';
const token = '<PERSONAL_ACCESS_TOKEN>'; // could also be an access token retrieved via OAuth

const body = {
  'argument1': 123,
  'argument2': 'my string',
  '$callMode': 'AsyncRequestReply' // optional argument to force call mode to AsyncRequestReply
}

// if invocation is done by GET, place the parameters in query string and remove the 'Content-Type' header
const invokeRequestOptions = {
  method: 'POST',
  headers: new Headers({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }),
  body: JSON.stringify(body),
};

const redirectRequestOptions = {
  method: "GET",
  credentials: 'same-origin',
  headers: new Headers({ Authorization: `Bearer ${token}` }),
  redirect: "follow", // this option must be set to follow, otherwise an 'opaqueredirect' response is returned
};

const response = await fetch(url, invokeRequestOptions);
let newLocation = response.headers.get("Location");

// first response should be 202 and have a location header
console.log(`Got ${response.status}, with location: ${newLocation}`);

for (let i = 0; i < 20; i++) {
  await sleep(SLEEP_DURATION);

  // follow the location header to the new endpoint
  const statusResponse = await fetch(newLocation, redirectRequestOptions);

  // if the response was redirected (and automatically followed), then the output endpoint has been reached
  // the output of the job can be found in the body of the response in JSON format
  if (statusResponse.status != 200 || statusResponse.redirected)
  {
    // read the job output
    const output = await statusResponse.json();
    console.log(`Got ${statusResponse.status}, with body: ${JSON.stringify(output)}`);

    break;
}

C# 示例

此示例说明如何从基于 C# 的应用程序中,通过 API 触发器使用“异步轮询”调用模式启动作业。

public async Task<string> AsyncPollingExample()
{
    const string url = "https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>";
    const string token = "<PERSONAL_ACCESS_TOKEN>"; // could also be an access token retrieved via OAuth

    // create an http client that does not follow redirects and adds a bearer token on each call
    var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var arguments = new Dictionary<string, object>
    {
        { "argument1", 123 },
        { "argument2", "my string" },
        { "$callMode", "AsyncRequestReply" }, // optional argument to force call mode to AsyncRequestReply
    };

    var httpResponseStart = await httpClient.PostAsJsonAsync(url, arguments);
    var redirectUri = httpResponseStart.Headers.Location;

    if (httpResponseStart.StatusCode != HttpStatusCode.Accepted)
        throw new Exception("Could not invoke workflow");

    while (true)
    {
        var httpPollingResponse = await httpClient.GetAsync(redirectUri);

        if (httpPollingResponse.StatusCode == HttpStatusCode.Redirect)
        {
            var outputLocation = httpPollingResponse.Headers.Location;
            var outputResponse = await httpClient.GetAsync(outputLocation);
            var jobOutput = await outputResponse.Content.ReadAsStringAsync();

            return jobOutput;
        }

        await Task.Delay(1000);
    }
}public async Task<string> AsyncPollingExample()
{
    const string url = "https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>";
    const string token = "<PERSONAL_ACCESS_TOKEN>"; // could also be an access token retrieved via OAuth

    // create an http client that does not follow redirects and adds a bearer token on each call
    var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var arguments = new Dictionary<string, object>
    {
        { "argument1", 123 },
        { "argument2", "my string" },
        { "$callMode", "AsyncRequestReply" }, // optional argument to force call mode to AsyncRequestReply
    };

    var httpResponseStart = await httpClient.PostAsJsonAsync(url, arguments);
    var redirectUri = httpResponseStart.Headers.Location;

    if (httpResponseStart.StatusCode != HttpStatusCode.Accepted)
        throw new Exception("Could not invoke workflow");

    while (true)
    {
        var httpPollingResponse = await httpClient.GetAsync(redirectUri);

        if (httpPollingResponse.StatusCode == HttpStatusCode.Redirect)
        {
            var outputLocation = httpPollingResponse.Headers.Location;
            var outputResponse = await httpClient.GetAsync(outputLocation);
            var jobOutput = await outputResponse.Content.ReadAsStringAsync();

            return jobOutput;
        }

        await Task.Delay(1000);
    }
}

异步触发与忽略

成功创建作业后,“触发与忽略”调用模式将返回 200 OK 状态,但不会返回有关该作业的任何其他信息。

“异步触发与忽略”工作流,在此工作流中,无需中间调用即可完成作业

docs image

JavaScript 示例

此示例说明如何从浏览器中,通过 API 触发器使用“异步触发与忽略”调用模式启动作业。

const url = 'https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>';
const token = '<PERSONAL_ACCESS_TOKEN>'; // could also be an access token retrieved via OAuth
  
const body = {
  'argument1': 123,
  'argument2': 'my string',
  '$callMode': 'FireAndForget' // optional argument to force call mode to FireAndForget
}

const options = {
  method: 'POST',
  headers: new Headers({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }),
  body: JSON.stringify(body),
};

let response = await fetch(url, options);

console.log(`Got ${response.status}`);const url = 'https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>';
const token = '<PERSONAL_ACCESS_TOKEN>'; // could also be an access token retrieved via OAuth
  
const body = {
  'argument1': 123,
  'argument2': 'my string',
  '$callMode': 'FireAndForget' // optional argument to force call mode to FireAndForget
}

const options = {
  method: 'POST',
  headers: new Headers({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }),
  body: JSON.stringify(body),
};

let response = await fetch(url, options);

console.log(`Got ${response.status}`);

C# 示例

此示例说明如何从基于 C# 的应用程序中,通过 API 触发器使用“异步触发与忽略”调用模式启动作业。

public async Task FireAndForgetExample()
{
    const string url = "https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>";
    const string token = "<PERSONAL_ACCESS_TOKEN>"; // could also be an access token retrieved via OAuth

    // create an http client that does not follow redirects and adds Bearer <token> on each call
    // if the follow redirects option is enabled, C# will not add a bearer token by default after the redirect
    var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var arguments = new Dictionary<string, object>
    {
        { "argument1", 123 },
        { "argument2", "my string" },
        { "$callMode", "FireAndForget" }, // optional argument to force call mode to LongPolling
    };

    var response = await httpClient.PostAsJsonAsync(url, arguments);

    Console.WriteLine(response.StatusCode);
}public async Task FireAndForgetExample()
{
    const string url = "https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>";
    const string token = "<PERSONAL_ACCESS_TOKEN>"; // could also be an access token retrieved via OAuth

    // create an http client that does not follow redirects and adds Bearer <token> on each call
    // if the follow redirects option is enabled, C# will not add a bearer token by default after the redirect
    var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var arguments = new Dictionary<string, object>
    {
        { "argument1", 123 },
        { "argument2", "my string" },
        { "$callMode", "FireAndForget" }, // optional argument to force call mode to LongPolling
    };

    var response = await httpClient.PostAsJsonAsync(url, arguments);

    Console.WriteLine(response.StatusCode);
}

同步 (长轮询)

此调用模式涉及一次初始调用,该调用会阻止并等待一段时间让作业完成,然后进行几次可能的阻塞调用和重定向。最后,在作业完成后,检索作业结果(输出或错误)。

根据租户设置,可能需要对所有调用进行身份验证,也可能只需要对初始调用进行身份验证。

“同步 (长轮询)”工作流,在此工作流中,无论成功与否,结果都会随初始调用一起返回

docs image

“同步 (长轮询)”工作流,在此工作流中,系统会自动发出多次调用直到作业完成

docs image

系统将使用已配置的 HTTP 谓词(GET、POST、PUT、DELETE)发出初始调用,这会在 Orchestrator 中创建关联的作业。成功创建作业后,系统会在等待作业完成的同时阻止当前调用。作业完成后,系统将释放阻止的调用,并发回包含作业输出参数的响应。

如果作业在超时期限后尚未完成,则系统会以 HTTP 状态代码 303(查看其他)作为响应,并重定向到状态 URI(通过 Location 标头)。您应定向到状态 URI,在作业完成之前,该状态 URI 将被阻止。如果作业在超时后仍未完成,系统会再次将您重定向到状态 URI,从而创建重定向循环。作业成功完成后,将检索作业结果(输出或错误)作为 HTTP 响应的一部分。

默认情况下,所有调用都需要包含有效的持有者令牌以进行授权。但是,如果未选择租户设置选项“同步 API 触发器重定向需要身份验证标头”,则只有对触发器的初始调用才需要身份验证标头。即使没有授权标头,也可以对状态端点进行后续调用。

此调用模式的最长作业持续时间为 15 分钟。

JavaScript 示例

此示例说明如何从浏览器中,通过 API 触发器使用“同步 (长轮询)”调用模式启动作业。

const url = 'https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>';
const token = '<PERSONAL_ACCESS_TOKEN>'; // could also be an access token retrieved via OAuth

const body = {
  'argument1': 123,
  'argument2': 'my string',
  '$callMode': 'LongPolling' // optional argument to force call mode to LongPolling
}

const options = {
  method: 'POST',
  headers: new Headers({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }),
  body: JSON.stringify(body),
  redirect: "follow", // follow redirects automatically
};

let response = await fetch(url, options);
const output = await response.json();

console.log(`Got ${response.status} with body ${JSON.stringify(output)}`);const url = 'https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>';
const token = '<PERSONAL_ACCESS_TOKEN>'; // could also be an access token retrieved via OAuth

const body = {
  'argument1': 123,
  'argument2': 'my string',
  '$callMode': 'LongPolling' // optional argument to force call mode to LongPolling
}

const options = {
  method: 'POST',
  headers: new Headers({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }),
  body: JSON.stringify(body),
  redirect: "follow", // follow redirects automatically
};

let response = await fetch(url, options);
const output = await response.json();

console.log(`Got ${response.status} with body ${JSON.stringify(output)}`);

C# 示例

此示例说明如何从基于 C# 的应用程序中,通过 API 触发器使用“同步 (长轮询)”调用模式启动作业。

public async Task SyncExample()
{
    const string url = "https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>";
    const string token = "<PERSONAL_ACCESS_TOKEN>"; // could also be an access token retrieved via OAuth

    // create an http client that does not follow redirects and adds Bearer <token> on each call
    // if the follow redirects option is enabled, C# will not add a bearer token by default after the redirect
    var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var arguments = new Dictionary<string, object>
    {
        { "argument1", 123 },
        { "argument2", "my string" },
        { "$callMode", "LongPolling" }, // optional argument to force call mode to LongPolling
    };

    var response = await httpClient.PostAsJsonAsync(url, arguments);

    while(response.StatusCode == HttpStatusCode.Redirect)
    {
        // in case of redirection, keep following the latest location in the header
        var location = response.Headers.Location;
        response = await httpClient.GetAsync(location);
    }

    // read the job output/error from the last request
    var jobOutput = response.Content.ReadAsStringAsync();

    Console.WriteLine(jobOutput);
}public async Task SyncExample()
{
    const string url = "https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>";
    const string token = "<PERSONAL_ACCESS_TOKEN>"; // could also be an access token retrieved via OAuth

    // create an http client that does not follow redirects and adds Bearer <token> on each call
    // if the follow redirects option is enabled, C# will not add a bearer token by default after the redirect
    var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var arguments = new Dictionary<string, object>
    {
        { "argument1", 123 },
        { "argument2", "my string" },
        { "$callMode", "LongPolling" }, // optional argument to force call mode to LongPolling
    };

    var response = await httpClient.PostAsJsonAsync(url, arguments);

    while(response.StatusCode == HttpStatusCode.Redirect)
    {
        // in case of redirection, keep following the latest location in the header
        var location = response.Headers.Location;
        response = await httpClient.GetAsync(location);
    }

    // read the job output/error from the last request
    var jobOutput = response.Content.ReadAsStringAsync();

    Console.WriteLine(jobOutput);
}
  • 异步轮询
  • JavaScript 示例
  • C# 示例
  • 异步触发与忽略
  • JavaScript 示例
  • C# 示例
  • 同步 (长轮询)
  • JavaScript 示例
  • C# 示例

此页面有帮助吗?

获取您需要的帮助
了解 RPA - 自动化课程
UiPath Community 论坛
Uipath Logo White
信任与安全
© 2005-2024 UiPath。保留所有权利。