HttpCurl Rust Reference Documentation

HttpCurl

Current Version: 11.6.1

curl-style HTTP requests with dependency resolution

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.

Define dependencies Use AddFunction with AddOutput or AddOutput2.
Manage variables Use SetVar, GetVar, ClearVar, and GetAllVars.
Preview execution Use ExaminePlan or ToRawRequest before sending.
Read responses Get text, binary, JSON, XML, or stream directly to a file.

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.

Note: 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.

Object Creation

// Cargo.toml:
//     [dependencies]
//     chilkat = "11.6"

use chilkat::HttpCurl;

// Once per process, before any other Chilkat call:
chilkat::unlock_bundle("Anything for 30-day trial")?;  // shorthand for Global::new().unlock_bundle(..)

let http_curl = HttpCurl::new();
// ... the native object is freed when `http_curl` goes out of scope.
pub fn new() -> HttpCurl

Creates the underlying native Chilkat object (HttpCurl also implements Default). Every method takes &self, so the object never needs to be declared mut. A HttpCurl is Send but not Sync: it may be moved to another thread, but a reference to it cannot be shared between threads at the same time.

impl Drop for HttpCurl

The native object is freed when the HttpCurl is dropped — when it goes out of scope, or explicitly with drop(http_curl). There is no Dispose method to call.

Errors

Methods that can fail return chilkat::Result<T>, which is Result<T, chilkat::Error>: a method whose only outcome is success or failure returns Result<()>, a method producing a string or an object returns Result<String> or Result<HttpCurl>. The error carries the object's LastErrorText at the time of the failure (Error::last_error_text), the class and method names, and implements std::error::Error, so ? works in any function returning chilkat::Result or a Box<dyn Error>. Properties never fail, and methods that answer a question (has_..., is_..., ...) return a plain bool.

match http_curl.some_method(...) {
    Ok(value) => println!("{value:?}"),
    Err(e) => eprintln!("{}", e.last_error_text()),
}

Properties

DebugLogFilePath
// read/write
pub fn debug_log_file_path(&self) -> String
pub fn set_debug_log_file_path(&self, value: &str)

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.

More Information and Examples
top
EnableBodyVars
// read/write
pub fn enable_body_vars(&self) -> bool
pub fn set_enable_body_vars(&self, value: bool)
Introduced in version 11.5.0

Enables variable substitution in the body of the request. The default value is true.

top
FailedCurl
// read-only
pub fn failed_curl(&self) -> String
Introduced in version 11.5.0

Set to the specific curl command in the execution plan that failed.

top
FailReason
// read-only
pub fn fail_reason(&self) -> i32
Introduced in version 11.5.0

Set to an integer value indicating the reason for failure for the methods DoYourThing and ExaminePlan

Possible values are:

  1. No error - the method succeeded or hasn't yet been called.
  2. curl command syntax error.
  3. HTTP response status code indidcates an authentication (401) or authorization (403) error.
  4. HTTP response status code indicates an error, but not an authentication or authorization error.
  5. HTTP communications failure.
  6. Impossible to derive an execution plan from defined outputs and inputs.
  7. A step in the execution plan did not resolve any dependency variables.
  8. Failed to get curl data from a local file source (see the note below).
  9. If we are within a Chilkat.Js context and don't have permission to read the local filesystem.
  10. Chilkat has not been successfully unlocked by previously and successfully calling UnlockBundle.
  11. 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.

top
HeartbeatMs
// read/write
pub fn heartbeat_ms(&self) -> i32
pub fn set_heartbeat_ms(&self, value: i32)
Introduced in version 11.5.0

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.

top
LastErrorHtml
// read-only
pub fn last_error_html(&self) -> String

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.

top
LastErrorText
// read-only
pub fn last_error_text(&self) -> String

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.

top
LastErrorXml
// read-only
pub fn last_error_xml(&self) -> String

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.

top
LastMethodSuccess
// read/write
pub fn last_method_success(&self) -> bool
pub fn set_last_method_success(&self, value: bool)

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.

top
ResponseBodyStr
// read-only
pub fn response_body_str(&self) -> String
Introduced in version 11.5.0

Returns the HTTP response body from the last call to DoYourThing .

top
ResponseFilePath
// read/write
pub fn response_file_path(&self) -> String
pub fn set_response_file_path(&self, value: &str)
Introduced in version 11.5.0

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 .

top
StatusCode
// read-only
pub fn status_code(&self) -> i32
Introduced in version 11.5.0

Returns the HTTP status code from the last call to DoYourThing. A value of 0 indicates no response header was received.

top
UncommonOptions
// read/write
pub fn uncommon_options(&self) -> String
pub fn set_uncommon_options(&self, value: &str)
Introduced in version 11.5.0

Provides a comma-separated list of uncommon option keywords.

This property defaults to an empty string and should normally remain empty.

top
VerboseLogging
// read/write
pub fn verbose_logging(&self) -> bool
pub fn set_verbose_logging(&self, value: bool)

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.

top
Version
// read-only
pub fn version(&self) -> String

Version of the component/library, such as "10.1.0"

More Information and Examples
top

Methods

AddFunction
pub fn add_function(&self, func_name: &str, curl: &str) -> Result<()>
Introduced in version 11.5.0

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 Ok(()) for success, Err(chilkat::Error) for failure.

More Information and Examples
top
AddOutput
pub fn add_output(&self, func_name: &str, json_path: &str, var_name: &str) -> Result<()>
Introduced in version 11.5.0

Adds or updates a defined output for a dependency resolution curl function previously defined by calling AddFunction. The json_path is the JSON path in the JSON response body where the var_name's value is located. If either the func_name or json_path already exist for the func_name, then the output is updated.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

More Information and Examples
top
AddOutput2
pub fn add_output2(&self, func_name: &str, array_path: &str, where_path: &str, where_value: &str, case_sensitive: bool, sub_path: &str, var_name: &str) -> Result<()>
Introduced in version 11.5.0

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 calling AddFunction. 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 at wherePath.
  • caseSensitive — If true, the comparison between whereValue and the JSON value is case-sensitive. If false, 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 Ok(()) for success, Err(chilkat::Error) for failure.

top
AddTargetOutput
pub fn add_target_output(&self, json_path: &str, var_name: &str)
Introduced in version 11.5.0

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 json_path is extracted (if present) and assigned to the variable named by var_name.

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.

More Information and Examples
top
ClearTargetOutput
pub fn clear_target_output(&self, var_name: &str)
Introduced in version 11.5.0

Clears (undefines) the target output for the specified var_name. If var_name equals "*", then all target outputs are cleared.

top
ClearVar
pub fn clear_var(&self, var_name: &str)
Introduced in version 11.5.0

Undefines the variable with the specified name. If var_name equals "*", then all variables are cleared.

top
DoYourThing
pub fn do_your_thing(&self, target_curl: &str) -> Result<()>
Introduced in version 11.5.0

Runs a the targetCurl command specified in target_curl. 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:

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 Ok(()) for success, Err(chilkat::Error) for failure.

top
ExaminePlan
pub fn examine_plan(&self, curl: &str, json: &JsonObject) -> Result<()>
Introduced in version 11.5.0

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 Ok(()) for success, Err(chilkat::Error) for failure.

top
GetAllVars
pub fn get_all_vars(&self, json: &JsonObject)
Introduced in version 11.5.0

Returns all defined variables in json.

More Information and Examples
top
GetResponseBd
pub fn get_response_bd(&self, bd: &BinData) -> Result<()>
Introduced in version 11.5.0

Appends to bd the HTTP response body from the last call to DoYourThing.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
GetResponseJarr
pub fn get_response_jarr(&self, jarr: &JsonArray) -> Result<()>
Introduced in version 11.5.0

Writes to jarr the HTTP response body from the last call to DoYourThing.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
GetResponseJson
pub fn get_response_json(&self, json: &JsonObject) -> Result<()>
Introduced in version 11.5.0

Writes to json the HTTP response body from the last call to DoYourThing.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
GetResponseSb
pub fn get_response_sb(&self, sb: &StringBuilder) -> Result<()>
Introduced in version 11.5.0

Appends to sb the HTTP response body from the last call to DoYourThing.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
GetResponseXml
pub fn get_response_xml(&self, xml: &Xml) -> Result<()>
Introduced in version 11.5.0

Writes to xml the HTTP response body from the last call to DoYourThing.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
GetVar
pub fn get_var(&self, var_name: &str) -> Result<String>
Introduced in version 11.5.0

Retrieves the current value of the variable specified by var_name.

Returns Err(chilkat::Error) on failure.

top
SetAuth
pub fn set_auth(&self, json: &JsonObject) -> Result<()>
Introduced in version 11.5.0

Sets authorization information that is applied to all calls to DoYourThing . See the examples below for details.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
SetVar
pub fn set_var(&self, var_name: &str, var_value: &str)
Introduced in version 11.5.0

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.

top
ToRawRequest
pub fn to_raw_request(&self, curl_command: &str, sb: &StringBuilder) -> Result<()>
Introduced in version 11.5.0

Used for debugging purposes. This method behaves the same as DoYourThing , but only converts the curl_command 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 Ok(()) for success, Err(chilkat::Error) for failure.

top
VarDefined
pub fn var_defined(&self, var_name: &str) -> bool
Introduced in version 11.5.0

Returns true if the var_name is defined, otherwise returns false. Setting var_name 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.

top

Events

All Chilkat methods are synchronous: the call returns when the work is done. During a call, HttpCurl raises three events so your application can show progress and offer a way out. Implement the chilkat::EventHandler trait (every method has a do-nothing default, so implement only the events you need) and install it with set_event_handler:

use chilkat::{HttpCurl, EventHandler};

struct Progress;

impl EventHandler for Progress {
    fn percent_done(&mut self, pct: i32) -> bool {
        println!("{pct}%");
        false   // return true to abort the method in progress
    }
    fn progress_info(&mut self, name: &str, value: &str) {
        println!("{name}: {value}");
    }
}

let http_curl = HttpCurl::new();
http_curl.set_event_handler(Progress);
http_curl.set_heartbeat_ms(250);   // raise abort_check 4 times per second during Chilkat calls

For a one-off handler the closure methods avoid writing a type; they may be combined, and each replaces the previously set closure for that one event (installing a closure removes a trait handler set earlier, and vice versa):

http_curl.on_percent_done(|pct| { println!("{pct}%"); false });
http_curl.on_progress_info(|name, value| println!("{name}: {value}"));
pub fn set_event_handler<H: EventHandler>(&self, handler: H)

Installs handler as the receiver of this object's events, replacing any handler or closures set earlier. The object owns the handler, which must be Send + 'static.

pub fn clear_event_handler(&self)

Removes the handler and any closures; events are no longer delivered.

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 abort_check or percent_done aborts the running method, which then returns Err.

Events fire on the thread that called the method, before that method returns. A panic inside a handler aborts the running method and is re-raised to the caller once the native library has returned, so it never unwinds through C frames. To abort a long operation from another thread, share an Arc<AtomicBool> with an abort_check handler, or set the object's AbortCurrent property to true.

AbortCheck
// EventHandler trait method; closure form: on_abort_check(FnMut() -> bool)
fn abort_check(&mut self) -> bool

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.

More Information and Examples

Example (closure form; the EventHandler trait method is equivalent):

http_curl.set_heartbeat_ms(250);   // call abort_check 4 times per second

let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let flag = stop.clone();
http_curl.on_abort_check(move || flag.load(std::sync::atomic::Ordering::Relaxed));
// ... another thread may now abort the method in progress with stop.store(true, Ordering::Relaxed)
top
PercentDone
// EventHandler trait method; closure form: on_percent_done(FnMut(i32) -> bool)
fn percent_done(&mut self, pct: i32) -> bool

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 pct_done 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 pct_done 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.

More Information and Examples

Example (closure form; the EventHandler trait method is equivalent):

http_curl.on_percent_done(|pct| {
    // pct ranges from 1 to 100.
    println!("Percent done: {pct}");
    false   // return true to abort the method in progress
});
top
ProgressInfo
// EventHandler trait method; closure form: on_progress_info(FnMut(&str, &str))
fn progress_info(&mut self, name: &str, value: &str)

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.

More Information and Examples

Example (closure form; the EventHandler trait method is equivalent):

http_curl.on_progress_info(|name, value| println!("{name}: {value}"));
top