Class HttpCurl
- All Implemented Interfaces:
AutoCloseable
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, request
bodies, the JSON paths that extract values from a response, and the local file path a
response is written to. 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.
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.
Event-capable: long-running methods report progress through a ProgressListener installed
with setProgressListener(ProgressListener), onAbortCheck(BooleanSupplier),
onPercentDone(IntPredicate) or onProgressInfo(BiConsumer).
Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when
done; an unclosed instance is freed when it becomes unreachable.
- See Also:
- Online reference
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddFunction(String funcName, String curl)Adds a named curl function that can be used in dependency resolution.voidAdds or updates a defined output for a dependency resolution curl function previously defined by calling.addFunction(String, String)voidaddOutput2(String funcName, String arrayPath, String wherePath, String whereValue, boolean caseSensitive, String subPath, String varName)Adds or updates an output variable definition for a dependency-resolution curl function previously created by callingAddFunction.voidaddTargetOutput(String jsonPath, String varName)Adds an automatically mapped variable for the target curl command.voidclearTargetOutput(String varName)Clears (undefines) the target output for the specifiedvarName.voidUndefines the variable with the specified name.voiddoYourThing(String targetCurl)Runs a thetargetCurlcommand specified intargetCurl.voidexaminePlan(String curl, JsonObject json)Used for debugging.voidgetAllVars(JsonObject json)Returns all defined variables injson.booleanEnables variable substitution in the body of the request.Set to the specific curl command in the execution plan that failed.intSet to an integer value indicating the reason for failure for the methodsanddoYourThing(String)examinePlan(String, JsonObject)intSpecifies the interval, in milliseconds, betweenAbortCheckevent callbacks.Returns the installed listener, ornull.voidgetResponseBd(BinData bd)Appends tobdthe HTTP response body from the last call to.doYourThing(String)Returns the HTTP response body from the last call to.doYourThing(String)Set this property to the path of a file to stream the response body to a file.Returns the HTTP response header from the last call to: the status line (such asdoYourThing(String)HTTP/1.1 200 OK) followed by the header fields, with CRLF line endings.getResponseHeaderField(String name)Returns the value of the response header field namedname(case-insensitive) from the last call to, such asdoYourThing(String)"Content-Type"or"ETag".voidgetResponseJarr(JsonArray jarr)Writes tojarrthe HTTP response body from the last call to.doYourThing(String)voidgetResponseJson(JsonObject json)Writes tojsonthe HTTP response body from the last call to.doYourThing(String)voidAppends tosbthe HTTP response body from the last call to.doYourThing(String)voidgetResponseXml(Xml xml)Writes toxmlthe HTTP response body from the last call to.doYourThing(String)intReturns the HTTP status code from the last call to.doYourThing(String)Provides a comma-separated list of uncommon option keywords.Retrieves the current value of the variable specified byvarName.voidonAbortCheck(BooleanSupplier callback)Installs a listener whose only callback isabortCheck: called everyHeartbeatMsmilliseconds during a long-running method; returntrueto abort it.voidonPercentDone(IntPredicate callback)Installs a listener whose only callback ispercentDone: called with the completion percentage (0..100) as a long-running method progresses; returntrueto abort it.voidonProgressInfo(BiConsumer<String,String> callback)Installs a listener whose only callback isprogressInfo: called with a name/value pair of progress information as a long-running method proceeds.voidsetAuth(JsonObject json)Sets authorization information that is applied to all calls to.doYourThing(String)voidsetEnableBodyVars(boolean value)Sets theEnableBodyVarsproperty; seegetEnableBodyVars().voidsetHeartbeatMs(int value)Sets theHeartbeatMsproperty; seegetHeartbeatMs().voidsetProgressListener(ProgressListener listener)Installs the listener that receives this object's progress events (abortCheck,percentDone,progressInfo) during its long-running methods; replaces any listener or lambda installed before;nullremoves it.voidsetResponseFilePath(String value)Sets theResponseFilePathproperty; seegetResponseFilePath().voidsetUncommonOptions(String value)Sets theUncommonOptionsproperty; seegetUncommonOptions().voidSets the value of a variable to be replaced in curl commands.voidtoRawRequest(String curlCommand, StringBuilder sb)Used for debugging purposes.booleanvarDefined(String varName)Returnstrueif thevarNameis defined, otherwise returnsfalse.Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
HttpCurl
public HttpCurl()Creates a newHttpCurlobject.
-
-
Method Details
-
getEnableBodyVars
public boolean getEnableBodyVars()Enables variable substitution in the body of the request. The default value istrue.- Returns:
- the value of the
EnableBodyVarsproperty
-
setEnableBodyVars
public void setEnableBodyVars(boolean value)Sets theEnableBodyVarsproperty; seegetEnableBodyVars().- Parameters:
value- the new value
-
getFailReason
public int getFailReason()Set to an integer value indicating the reason for failure for the methodsanddoYourThing(String)examinePlan(String, JsonObject)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).
- The response body is compressed with a Content-Encoding Chilkat cannot decode, such as Brotli
(
br) or zstd, so it is unusable. gzip and deflate are decoded automatically. (Introduced in v11.7.0.)
Note:
curlcan 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
@tellscurlto load the data from a local file instead of using a literal string.- Returns:
- the value of the
FailReasonproperty (read-only)
-
getFailedCurl
Set to the specific curl command in the execution plan that failed.- Returns:
- the value of the
FailedCurlproperty (read-only)
-
getHeartbeatMs
public int getHeartbeatMs()Specifies the interval, in milliseconds, betweenAbortCheckevent callbacks.This allows an application to periodically decide whether a long-running operation should be aborted.
The default value is
0, which means noAbortCheckcallbacks are generated.- Returns:
- the value of the
HeartbeatMsproperty
-
setHeartbeatMs
public void setHeartbeatMs(int value)Sets theHeartbeatMsproperty; seegetHeartbeatMs().- Parameters:
value- the new value
-
getResponseBodyStr
Returns the HTTP response body from the last call to.doYourThing(String)- Returns:
- the value of the
ResponseBodyStrproperty (read-only)
-
getResponseFilePath
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,getResponseBodyStr(), orgetResponseSb(StringBuilder).getResponseBd(BinData)- Returns:
- the value of the
ResponseFilePathproperty
-
setResponseFilePath
Sets theResponseFilePathproperty; seegetResponseFilePath().- Parameters:
value- the new value (notnull)
-
getResponseHeader
Returns the HTTP response header from the last call to: the status line (such asdoYourThing(String)HTTP/1.1 200 OK) followed by the header fields, with CRLF line endings. Empty if no response was received. When redirects were followed (-L), this is the header of the final response. To get a single field, use. The curlgetResponseHeaderField(String)-D/--dump-headeroption writes the header of every response (including redirects) to a file, and-i/--includewrites the header before the body in the-o/-Ooutput file; neither changes this property or the response body returned in memory.- Returns:
- the value of the
ResponseHeaderproperty (read-only)
-
getStatusCode
public int getStatusCode()Returns the HTTP status code from the last call to. A value ofdoYourThing(String)0indicates no response header was received.- Returns:
- the value of the
StatusCodeproperty (read-only)
-
getUncommonOptions
Provides a comma-separated list of uncommon option keywords.This property defaults to an empty string and should normally remain empty.
Can be set to a list of the following comma separated keywords:
IgnoreUnknownCurlOptions- Introduced in v11.7.0. Starting in v11.7.0, a curl option that HttpCurl does not recognize causesto fail with a syntax error (doYourThing(String)= 1) naming the option ingetFailReason()LastErrorText, rather than being silently dropped as in earlier versions. (Options that are meaningless to HttpCurl but harmless, such as--progress-baror--retry, are accepted and ignored.) This keyword restores the earlier behavior: an unknown option is skipped with a note inLastErrorText. Note that the value of an unknown option that takes one is then seen as a stray token.
- Returns:
- the value of the
UncommonOptionsproperty
-
setUncommonOptions
Sets theUncommonOptionsproperty; seegetUncommonOptions().- Parameters:
value- the new value (notnull)
-
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(String, String, String)- Parameters:
funcName- thefuncNameargument (notnull)curl- thecurlargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
addOutput
Adds or updates a defined output for a dependency resolution curl function previously defined by calling. TheaddFunction(String, String)jsonPathis the JSON path in the JSON response body where thevarName's value is located. If either thefuncNameorjsonPathalready exist for thefuncName, then the output is updated.- Parameters:
funcName- thefuncNameargument (notnull)jsonPath- thejsonPathargument (notnull)varName- thevarNameargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
addOutput2
public void addOutput2(String funcName, String arrayPath, String wherePath, String whereValue, boolean caseSensitive, String subPath, String varName)Adds or updates an output variable definition for a dependency-resolution curl function previously created by callingAddFunction. 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 atwherePathmatcheswhereValue, and then extracts the value atsubPath. The extracted value is assigned to the variable named byvarName.The
wherePathandsubPathvalues are paths relative to each individual array element. The comparison betweenwhereValueand the JSON value found atwherePathis either case-sensitive or case-insensitive depending on the value ofcaseSensitive.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. May contain variable references (see below). -
wherePath— A relative JSON path within each array element used to locate the matching record. May contain variable references (see below). -
whereValue— The value to match against the JSON value found atwherePath. May contain variable references (see below). -
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. May contain variable references (see below). -
varName— The name of the variable that will receive the extracted value.
Variable references
Starting in v11.7.0, the
arrayPath,wherePath,whereValueandsubPathmay each contain variable names enclosed in{{and}}, such as{{site_name}}, either on their own or within a longer string such asresult.{{list_name}}.items. Each is stored exactly as passed here, and the references in it are resolved every time this output is evaluated — not whenAddOutput2is called. A variable whose value is set later bySetVar, or that is produced as the output of another curl function, is therefore used with its current value.A variable referenced here is treated as an input of the curl function, exactly like one appearing in the curl command itself, so the execution plan runs whatever produces it first. If a referenced variable has no value and nothing can produce it, the reference is left in place, no array element matches, and the LastErrorText reports the failure with both the resolved and the unresolved form of the record spec.
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
drivesarray for the element whosenamematches"shared"using case-insensitive comparison. The matching element is:{ "name": "Shared", "id": "B456" }The value of
idis extracted and assigned to the variabledrive_id, resulting in:drive_id = "B456"
- Parameters:
funcName- thefuncNameargument (notnull)arrayPath- thearrayPathargument (notnull)wherePath- thewherePathargument (notnull)whereValue- thewhereValueargument (notnull)caseSensitive- thecaseSensitiveargumentsubPath- thesubPathargument (notnull)varName- thevarNameargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
-
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 byjsonPathis extracted (if present) and assigned to the variable named byvarName.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.
- Parameters:
jsonPath- thejsonPathargument (notnull)varName- thevarNameargument (notnull)
-
clearTargetOutput
Clears (undefines) the target output for the specifiedvarName. IfvarNameequals"*", then all target outputs are cleared.- Parameters:
varName- thevarNameargument (notnull)
-
clearVar
Undefines the variable with the specified name. IfvarNameequals"*", then all variables are cleared.- Parameters:
varName- thevarNameargument (notnull)
-
doYourThing
Runs a thetargetCurlcommand specified intargetCurl. If thetargetCurlcontains 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 thetargetCurlcommand.Returns success (
true) if a response was received, in which case the response status code will be available inand the content of the response body will be available in one of two places:getStatusCode()- If
is non-empty, the response body was streamed to the specified file path.getResponseFilePath() - If
is empty, the response body can be retrieved viagetResponseFilePath(),getResponseBodyStr(), orgetResponseSb(StringBuilder). Binary responses should only be retrieved viagetResponseBd(BinData).ResponseBodyBd
Assuming the HTTP response is JSON, the target outputs (variables) specified by prior calls to
will be populated by applying each variable's JSON path to the response JSON.addTargetOutput(String, String)Writing the response to a local file
A curl command may write the response body to a local file with
-o/--output(an explicit filename), or with-O/--remote-name(the filename is the final path segment of the URL). Either may be combined with--output-dir, which, as in curl, is applied only when the filename itself contains no directory separator.Starting in v11.7.0, the output file path may contain variable names enclosed in
{{and}}, resolved from the current variable values at the time the request is sent. This applies to the path given with-o, the directory given with--output-dir, and the URL that-Oderives a filename from. In previous versions the path was used exactly as written, so-o "{{report_name}}.pdf"created a file literally named{{report_name}}.pdfand reported success.httpCurl.SetVar("customer","acme"); httpCurl.SetVar("report_name","q3-summary"); httpCurl.DoYourThing("curl https://api.example.com/reports/{{report_name}} " "--output-dir \"reports/{{customer}}\" -o \"{{report_name}}.pdf\""); // writes reports/acme/q3-summary.pdfTwo conditions cause the request to fail rather than write a file:
- The resolved path still contains a
{{varName}}reference, or a variable in it resolved to an empty string. (Elsewhere -- in a URL or a request body -- an unresolved reference is left in place. In a file path that would silently create a misnamed file.) - A variable substituted into the path has a value containing a
..directory segment. Because a variable's value can come from a server's response (seeandaddOutput(String, String, String)), a response must not be able to move the output file out of the directory the curl command named. AaddOutput2(String, String, String, String, boolean, String, String)..written literally in the curl command itself is the application's own choice and is allowed.
The path as it will actually be used is written to
LastErrorTextasresolvedOutputPath.This is independent of the
property, which streams the response body to a file for requests whose curl command names no output file.getResponseFilePath()- Parameters:
targetCurl- thetargetCurlargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
- If
-
examinePlan
Used for debugging. Returns injsonthe plan of execution that would occur for thecurlbased on the variables that are either unknown or already known. The plan of execution is what would occur ifwas called with the current state of knowledge.doYourThing(String)If no execution plan is possible with the current known inputs and outputs, then
jsonprovides information about what is missing and the method returnsfalse.- Parameters:
curl- thecurlargument (notnull)json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getAllVars
Returns all defined variables injson.- Parameters:
json- thejsonargument (notnull)
-
getResponseBd
Appends tobdthe HTTP response body from the last call to.doYourThing(String)- Parameters:
bd- thebdargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getResponseHeaderField
Returns the value of the response header field namedname(case-insensitive) from the last call to, such asdoYourThing(String)"Content-Type"or"ETag". Returns an empty string if the response has no such field. When redirects were followed (-L), the field is from the final response. The full response header is available in.getResponseHeader()- Parameters:
name- thenameargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getResponseJarr
Writes tojarrthe HTTP response body from the last call to.doYourThing(String)- Parameters:
jarr- thejarrargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getResponseJson
Writes tojsonthe HTTP response body from the last call to.doYourThing(String)- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getResponseSb
Appends tosbthe HTTP response body from the last call to.doYourThing(String)- Parameters:
sb- thesbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getResponseXml
Writes toxmlthe HTTP response body from the last call to.doYourThing(String)- Parameters:
xml- thexmlargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getVar
Retrieves the current value of the variable specified byvarName.- Parameters:
varName- thevarNameargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAuth
Sets authorization information that is applied to all calls to. See the examples below for details.doYourThing(String)- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
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. Starting in v11.7.0, they can also occur in thearrayPath,wherePath,whereValueandsubPathpassed to, and in the local output file path of a curl command -- the path given withaddOutput2(String, String, String, String, boolean, String, String)-oor--output, the directory given with--output-dir, and the URL that-Oderives a filename from. See.doYourThing(String)- Parameters:
varName- thevarNameargument (notnull)varValue- thevarValueargument (notnull)
-
toRawRequest
Used for debugging purposes. This method behaves the same as, but only converts thedoYourThing(String)curlCommandto an HTTP request message insbcontaining the full structure:- start line
- headers
- optional body or multipart body
It does not actually send the HTTP request.
- Parameters:
curlCommand- thecurlCommandargument (notnull)sb- thesbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
varDefined
Returnstrueif thevarNameis defined, otherwise returnsfalse. SettingvarNameto"!"checks whether all target output variables have been defined. It returnstrueif every target output is set, andfalseif any are missing.- Parameters:
varName- thevarNameargument (notnull)- Returns:
- the result; this method never throws
ChilkatException
-
setProgressListener
Installs the listener that receives this object's progress events (abortCheck,percentDone,progressInfo) during its long-running methods; replaces any listener or lambda installed before;nullremoves it.- Parameters:
listener- the listener, ornull- Throws:
IllegalStateException- if called from inside one of this object's own callbacks
-
getProgressListener
Returns the installed listener, ornull.- Returns:
- the listener installed with
setProgressListener(ProgressListener)or one of theon...methods
-
onAbortCheck
Installs a listener whose only callback isabortCheck: called everyHeartbeatMsmilliseconds during a long-running method; returntrueto abort it. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-
onPercentDone
Installs a listener whose only callback ispercentDone: called with the completion percentage (0..100) as a long-running method progresses; returntrueto abort it. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-
onProgressInfo
Installs a listener whose only callback isprogressInfo: called with a name/value pair of progress information as a long-running method proceeds. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-