HttpCurl Dart Reference Documentation
CkHttpCurl
Current Version: 11.6.1
Run curl commands and automatically resolve values needed by later requests
The Chilkat.HttpCurl class executes HTTP requests expressed as curl
commands, with support for variable substitution, reusable curl functions, automatic
dependency resolution, response extraction, and structured diagnostics.
Variables such as {{access_token}}, {{site_id}}, or
{{drive_id}} can appear in URLs, headers, query parameters, or request
bodies. If a variable is not yet known, HttpCurl can build an execution
plan from previously defined curl functions, run the prerequisite requests, extract
values from JSON responses, and then execute the final target request.
AddFunction with AddOutput or AddOutput2.
SetVar, GetVar, ClearVar, and GetAllVars.
ExaminePlan or ToRawRequest before sending.
After DoYourThing completes, check StatusCode and retrieve
the response using the appropriate getter. If something fails,
FailReason, FailedCurl, and LastErrorText
help identify the failed step and the reason.
Chilkat.HttpCurl is not derived from curl/libcurl and does not wrap
libcurl. It accepts curl-style command text and executes the request using Chilkat’s
own HTTP implementation.
For an extended overview, see HttpCurl Class Overview.
See also:
- HttpCurl Overview — concepts, variable substitution, dependency resolution, and workflow examples.
- Dependency Engine — how execution plans are derived, unknown variables are resolved, and cached variables are managed.
Object Creation
// pubspec.yaml:
// dependencies:
// chilkat: ^11.6.1
import 'package:chilkat/chilkat.dart';
// Once per process, before any other Chilkat call:
Chilkat.unlockBundle('Anything for 30-day trial'); // shorthand for CkGlobal().unlockBundle(..)
final httpCurl = CkHttpCurl();
// ... the native object is released when `httpCurl` is garbage collected, or now with httpCurl.dispose().Creates the underlying native Chilkat object. Use a CkHttpCurl only from the isolate that created it: Chilkat objects cannot be sent between isolates. Every call is synchronous; in a Flutter app, run long operations (network, large files) inside Isolate.run, creating the Chilkat objects inside the isolate.
Releases the native object immediately instead of waiting for garbage collection (useful for a large CkBinData or an open socket). Calling it more than once is harmless; any other use of the object afterwards throws a StateError. isDisposed tells whether it has been called.
Errors
A method that can fail throws a ChilkatException: a method whose only outcome is success or failure returns void and throws on failure; a method producing a String or an object returns it and throws where Chilkat would have returned null. The exception carries the object's LastErrorText at the time of the failure (lastErrorText), the class and method names (className, methodName) and a one-line message. Properties never throw, and methods that answer a question (has..., is..., ...) return a plain bool.
try {
httpCurl.someMethod(...);
} on ChilkatException catch (e) {
print(e); // CkHttpCurl.someMethod failed: <reason>
print(e.lastErrorText); // the full Chilkat log of the failed call
}
Properties
DebugLogFilePath
String get debugLogFilePath
set debugLogFilePath(String value)
If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.
Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.
Possible causes of hangs include:
- A timeout property set to 0, indicating an infinite timeout.
- A hang occurring within an event callback in the application code.
- An internal bug in the Chilkat code causing the hang.
EnableBodyVars
bool get enableBodyVars
set enableBodyVars(bool value)
Enables variable substitution in the body of the request. The default value is true.
FailedCurl
String get failedCurl
Set to the specific curl command in the execution plan that failed.
topFailReason
int get failReason
Set to an integer value indicating the reason for failure for the methods DoYourThing and ExaminePlan
Possible values are:
- No error - the method succeeded or hasn't yet been called.
- curl command syntax error.
- HTTP response status code indidcates an authentication (401) or authorization (403) error.
- HTTP response status code indicates an error, but not an authentication or authorization error.
- HTTP communications failure.
- Impossible to derive an execution plan from defined outputs and inputs.
- A step in the execution plan did not resolve any dependency variables.
- Failed to get curl data from a local file source (see the note below).
- If we are within a
Chilkat.Jscontext and don't have permission to read the local filesystem. - Chilkat has not been successfully unlocked by previously and successfully calling UnlockBundle.
- Failed to open or create the local output file (if a curl option directed output to a file).
Note: curl can read data from a local file and send it in a request (usually POST/PUT) using special syntax:
-d @file.txt→ reads the file and sends it as request body (form-style encoding).--data-binary @file.bin→ sends raw file contents exactly as-is.-F "file=@file.txt"→ uploads the file as multipart/form-data.
The @ tells curl to load the data from a local file instead of using a literal string.
HeartbeatMs
int get heartbeatMs
set heartbeatMs(int value)
Specifies the interval, in milliseconds, between AbortCheck
event callbacks.
This allows an application to periodically decide whether a long-running operation should be aborted.
The default value is 0, which means no AbortCheck
callbacks are generated.
LastErrorHtml
String get lastErrorHtml
Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastErrorText
String get lastErrorText
Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
LastErrorXml
String get lastErrorXml
Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastMethodSuccess
bool get lastMethodSuccess
set lastMethodSuccess(bool value)
Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.
ResponseBodyStr
String get responseBodyStr
Returns the HTTP response body from the last call to DoYourThing .
ResponseFilePath
String get responseFilePath
set responseFilePath(String value)
Set this property to the path of a file to stream the response body to a file. If the response is streamed to a file, it will not be available in ResponseBodyStr , GetResponseSb , or GetResponseBd .
StatusCode
int get statusCode
Returns the HTTP status code from the last call to DoYourThing. A value of 0 indicates no response header was received.
UncommonOptions
String get uncommonOptions
set uncommonOptions(String value)
Provides a comma-separated list of uncommon option keywords.
This property defaults to an empty string and should normally remain empty.
topVerboseLogging
bool get verboseLogging
set verboseLogging(bool value)
If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
String get version
Methods
AddFunction
Adds a named curl function that can be used in dependency resolution. Inputs required by the curl function are indicated by the variable names enclosed in {{ and }}. Outputs are defined in one or more calls to AddOutput .
Returns normally on success; throws a ChilkatException on failure.
AddOutput
Adds or updates a defined output for a dependency resolution curl function previously defined by calling AddFunction. The jsonPath is the JSON path in the JSON response body where the varName's value is located. If either the funcName or jsonPath already exist for the funcName, then the output is updated.
Returns normally on success; throws a ChilkatException on failure.
AddOutput2
Adds or updates an output variable definition for a dependency-resolution curl function previously created by calling
AddFunction.
Use this method when the curl response is JSON containing an array of objects, and a value needs to be extracted
from one specific array element.
The method searches the array located at arrayPath, finds the array element where the value at
wherePath matches whereValue, and then extracts the value at subPath.
The extracted value is assigned to the variable named by varName.
The wherePath and subPath values are paths relative to each individual array element.
The comparison between whereValue and the JSON value found at wherePath is either
case-sensitive or case-insensitive depending on the value of caseSensitive.
Parameters
-
funcName— The name of the curl function previously added by callingAddFunction. The output definition is associated with this function. -
arrayPath— The JSON path identifying the array of records within the JSON response. -
wherePath— A relative JSON path within each array element used to locate the matching record. -
whereValue— The value to match against the JSON value found atwherePath. -
caseSensitive— Iftrue, the comparison betweenwhereValueand the JSON value is case-sensitive. Iffalse, the comparison is case-insensitive. -
subPath— A relative JSON path within the matched array element identifying the value to extract. -
varName— The name of the variable that will receive the extracted value.
Example
Given the following JSON response:
{
"drives": [
{
"name": "Documents",
"id": "A123"
},
{
"name": "Shared",
"id": "B456"
}
]
}
The following call:
AddOutput2("GetDrive","drives","name","shared",false,"id","drive_id")
searches the drives array for the element whose name matches
"shared" using case-insensitive comparison. The matching element is:
{
"name": "Shared",
"id": "B456"
}
The value of id is extracted and assigned to the variable
drive_id, resulting in:
drive_id = "B456"
Returns normally on success; throws a ChilkatException on failure.
AddTargetOutput
Adds an automatically mapped variable for the target curl command. When a JSON response is received from a curl request, the value at the JSON path specified by jsonPath is extracted (if present) and assigned to the variable named by varName.
This is useful in common workflows where one request returns an identifier (such as an `id`) that must be reused in a subsequent curl request.
ClearTargetOutput
Clears (undefines) the target output for the specified varName. If varName equals "*", then all target outputs are cleared.
ClearVar
Undefines the variable with the specified name. If varName equals "*", then all variables are cleared.
DoYourThing
Runs a the targetCurl command specified in targetCurl. If the targetCurl contains variable names enclosed in {{ and }}, then an execution plan is constructed from defined functions and outputs to resolve unknown variables, and the execution plan is run. The final step in the execution plan is always the targetCurl command.
Returns success (true) if a response was received, in which case the response status code will be available in StatusCode and the content of the response body will be available in one of two places:
- If
ResponseFilePathis non-empty, the response body was streamed to the specified file path. - If
ResponseFilePathis empty, the response body can be retrieved viaResponseBodyStr,GetResponseSb, orGetResponseBd. Binary responses should only be retrieved viaResponseBodyBd.
Assuming the HTTP response is JSON, the target outputs (variables) specified by prior calls to AddTargetOutput will be populated by applying each variable's JSON path to the response JSON.
Returns normally on success; throws a ChilkatException on failure.
ExaminePlan
Used for debugging. Returns in json the plan of execution that would occur for the curl based on the variables that are either unknown or already known. The plan of execution is what would occur if DoYourThing was called with the current state of knowledge.
If no execution plan is possible with the current known inputs and outputs, then json provides information about what is missing and the method returns false.
Returns normally on success; throws a ChilkatException on failure.
GetAllVars
GetResponseBd
Appends to bd the HTTP response body from the last call to DoYourThing.
Returns normally on success; throws a ChilkatException on failure.
GetResponseJarr
Writes to jarr the HTTP response body from the last call to DoYourThing.
Returns normally on success; throws a ChilkatException on failure.
GetResponseJson
Writes to json the HTTP response body from the last call to DoYourThing.
Returns normally on success; throws a ChilkatException on failure.
GetResponseSb
Appends to sb the HTTP response body from the last call to DoYourThing.
Returns normally on success; throws a ChilkatException on failure.
GetResponseXml
Writes to xml the HTTP response body from the last call to DoYourThing.
Returns normally on success; throws a ChilkatException on failure.
GetVar
Retrieves the current value of the variable specified by varName.
Throws a ChilkatException on failure (where the description says null is returned, the Dart method throws instead).
SetAuth
Sets authorization information that is applied to all calls to DoYourThing . See the examples below for details.
Returns normally on success; throws a ChilkatException on failure.
SetVar
Sets the value of a variable to be replaced in curl commands. Variable names are enclosed in {{ and }} and can occur in the path, query params, or the body of the request.
ToRawRequest
Used for debugging purposes. This method behaves the same as DoYourThing , but only converts the curlCommand to an HTTP request message in sb containing the full structure:
- start line
- headers
- optional body or multipart body
It does not actually send the HTTP request.
Returns normally on success; throws a ChilkatException on failure.
VarDefined
Returns true if the varName is defined, otherwise returns false. Setting varName to "!" checks whether all target output variables have been defined. It returns true if every target output is set, and false if any are missing.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a call, CkHttpCurl raises three events so your application can show progress and offer a way out. Each event is a nullable callback property on the object; assign a function to receive it, or null to stop receiving it:
final httpCurl = CkHttpCurl();
httpCurl.onPercentDone = (pct) {
print('$pct%');
return false; // return true to abort the method in progress
};
httpCurl.onProgressInfo = (name, value) => print('$name: $value');
httpCurl.heartbeatMs = 250; // raise onAbortCheck 4 times per second during Chilkat calls
httpCurl.onAbortCheck = () => _userPressedCancel;AbortCheck fires at regular intervals controlled by the HeartbeatMs property (0, the default, disables it); PercentDone fires when an operation's completion percentage is known; ProgressInfo delivers named progress values. Returning true from onAbortCheck or onPercentDone aborts the running method, which then throws a ChilkatException.
Events fire on the thread that called the method, before that method returns. An exception thrown inside a callback aborts the running method and is rethrown from it once the native library has returned. In a Flutter app the callbacks run inside the worker isolate that owns the object; forward progress to the UI through a SendPort, and let onAbortCheck read a flag the UI sets the same way.
AbortCheck
bool Function()? onAbortCheck
Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.
Example:
httpCurl.heartbeatMs = 250; // call onAbortCheck 4 times per second
var cancelRequested = false;
httpCurl.onAbortCheck = () => cancelRequested;
// ... set cancelRequested = true (e.g. from a message received on a ReceivePort) to abort the method in progressPercentDone
bool Function(int pctDone)? onPercentDone
This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).
The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.
To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.
Example:
httpCurl.onPercentDone = (pct) {
// pct ranges from 1 to 100.
print('Percent done: $pct');
return false; // return true to abort the method in progress
};ProgressInfo
void Function(String name, String value)? onProgressInfo
This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.
Note: Some Chilkat methods don't fire any ProgressInfo events.
Example:
httpCurl.onProgressInfo = (name, value) => print('$name: $value');