Class Rest
- All Implemented Interfaces:
AutoCloseable
Build, send, authenticate, stream, and inspect REST API requests with precise control.
Chilkat.Rest is a flexible REST client class for applications
that need detailed control over request construction, connection reuse,
authentication, headers, query parameters, multipart bodies, streaming
uploads and downloads, response parsing, and low-level diagnostics. It is
especially useful for APIs where the application must carefully manage
provider-specific signing, request paths, body formats, and server responses.
Precise request construction
Build REST requests with explicit paths, headers, query parameters, request bodies, content types, and HTTP methods.
Connection reuse
Connect once and send multiple requests over the same underlying connection when appropriate.
Authentication support
Work with bearer tokens, OAuth2, AWS-style signing, Azure and Google auth helpers, and other service-specific authentication patterns.
Request bodies and multipart
Send JSON, XML, text, binary data, form parameters, multipart requests, streams, and file-based request bodies.
Response handling
Read response bodies as strings, bytes, streams, JSON, XML, or
StringBuilder content, and inspect status codes and headers.
Diagnostics and debugging
Use detailed error text, raw request generation, response headers, connection state, and verbose diagnostics to troubleshoot API behavior.
Choosing the right class:
Use Chilkat.Rest when you want fine-grained control over the
connection and request construction. For higher-level HTTP convenience
methods that accept full URLs directly, use Chilkat.Http. For
advanced socket routing, create the connection with Chilkat.Socket
and pass it to UseConnection.
Stateful request configuration:
Request headers, ordinary query parameters, path substitutions, multipart parts,
and authentication settings remain associated with the Rest object
until they are replaced or cleared. When reusing an object for unrelated requests,
call the applicable Clear* methods rather than assuming request state
is automatically reset.
Low-level response workflow:
After a SendReq* call, call ReadResponseHeader and then read
the response body exactly once when a body is present. Fully consume the body before
sending another request on the same connection. A HEAD response has no
body; a 204 No Content response is represented by an empty body.
Redirects and cookies:
The Rest class exposes redirect and response-header information but does
not automatically follow redirects or maintain a cookie jar. Applications should
process Location and Set-Cookie values explicitly when needed.
For an extended overview, see Rest Class Overview.
</section>
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 TypeMethodDescriptionvoidAdds an HTTP request header usingnameas the field name andvalueas the field value.voidaddMwsSignature(String httpVerb, String uriPath, String domain, String mwsSecretKey)Computes the Amazon Marketplace Web Service (MWS) request signature using the secret key inmwsSecretKeyand adds or replaces theSignaturequery parameter.voidaddPathParam(String name, String value)Adds or replaces a path-substitution parameter.voidaddQueryParam(String name, String value)Adds or replaces a query-string parameter usingnameas the parameter name andvalueas its value.voidaddQueryParams(String queryString)Adds multiple query parameters from the query-string text inqueryString.voidaddQueryParamSb(String name, StringBuilder value)Adds or replaces a query-string parameter named byname.voidRemoves all HTTP request headers previously added to this object.voidRemoves all multipart subparts from the request under construction.voidRemoves all path-substitution parameters previously added with.addPathParam(String, String)voidRemoves all query parameters previously added to this object.voidClears authentication providers and credentials previously configured through this class'sSetAuth*methods.voidClears the response-stream destination previously configured by.setResponseBodyStream(int, boolean, Stream)voidEstablishes the initial TCP connection to the REST server.voiddisconnect(int maxWaitMs)Closes the current HTTP connection, if one is open.voidfullRequestBd(String httpVerb, String uriPath, BinData binData, StringBuilder responseBody)Sends a complete request whose binary body is read from theBinDatainbinData.fullRequestFormUrlEncoded(String httpVerb, String uriPath)Sends a completeapplication/x-www-form-urlencodedrequest.fullRequestMultipart(String httpVerb, String uriPath)Sends a complete multipart request using the parts and part headers configured through,getPartSelector(), and the multipart-body methods.addHeader(String, String)fullRequestNoBody(String httpVerb, String uriPath)Sends a complete request with no request body.voidfullRequestNoBodyBd(String httpVerb, String uriPath, BinData binData)Sends a complete request without a request body and stores the binary response body in theBinDatainbinData, replacing its previous contents.voidfullRequestNoBodySb(String httpVerb, String uriPath, StringBuilder sb)Sends a complete request without a request body and stores the text response body in theStringBuilderinsb, replacing its previous contents.voidfullRequestSb(String httpVerb, String uriPath, StringBuilder requestBody, StringBuilder responseBody)Sends a complete request whose text body is read from theStringBuilderinrequestBody.fullRequestStream(String httpVerb, String uriPath, Stream stream)Sends a complete request whose body is read from theStreaminstream.fullRequestString(String httpVerb, String uriPath, String bodyText)Sends a complete request whose text body is supplied inbodyText, such as JSON, XML, or plain text.booleanControls whether long request-header fields may be folded onto continuation lines.booleanControls whether non-ASCII request-header values may be converted to RFC 2047 encoded-word form using Q or Base64 encoding.Gets or sets the value sent in the HTTPAuthorizationrequest header.intAfterfails, returns a code identifying the connection stage or TLS handshake stage that failed.connect(String, int, boolean, boolean)intGets or sets the maximum number of milliseconds to wait for the remote server to accept the TCP connection.booleanWhentrue, calls to theSend*andFullRequest*methods compose the complete request but do not transmit it.booleanControls automatic resolution of credentials from operating-system secure storage.intControls the interval, in milliseconds, betweenevent callbacks during supported long-running operations.AbortCheckgetHost()Gets or sets the value of the HTTPHostrequest header.intGets or sets the maximum number of milliseconds to wait when a send or receive operation has stopped making progress.voidCopies the fully composed HTTP request generated whilewasgetDebugMode()trueinto theBinDatainbd.voidgetLastJsonData(JsonObject json)Copies operation-specific diagnostic or result information from the most recently completed method into theJsonObjectinjson.Returns the redirect target from the most recently received response.Returns the HTTP header fields from the most recently composed request, excluding the request line.Returns the request line from the most recently composed request.intReturns the number of response header field occurrences.Selects the multipart entity or part targeted by multipart-building operations such asAddHeader,RemoveHeader, and theSetMultipartBody*methods.booleanApplies to the full-request methods that both upload a request and download a response.Returns the installed listener, ornull.Returns the HTTP response header fields from the most recently received response, excluding the status line.intReturns the numeric HTTP status code from the most recently received response, such as200,404, or503.Returns the reason phrase associated with the most recently received HTTP status code, such asOKorNot Found.booleanControls whether streaming uploads use aContent-Lengthheader instead of HTTP/1.1 chunked transfer encoding when the total body size is known.Provides opt-in compatibility settings for uncommon requirements.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.voidreadRespBd(BinData responseBody)Reads the response body as raw bytes into theBinDatainresponseBody, replacing its previous contents.voidreadRespBodyStream(Stream stream, boolean autoSetStreamCharset)Reads the response body into theStreamsupplied instream.Reads the response body as text and returns it.intreadRespChunkBd(int minSize, BinData bd)Afterhas been called, reads the next chunk of the response body and appends the received bytes to thereadResponseHeader()BinDatainbd.intReads the HTTP response status line and header fields.voidreadRespSb(StringBuilder responseBody)Reads the response body as text into theStringBuilderinresponseBody, replacing its previous contents.voidremoveHeader(String name)Removes all request headers named bynamefrom the request level selected by.getPartSelector()voidremoveQueryParam(String name)Removes all query parameters whose name matchesname.responseHdrByName(String name)Returns the value of the response header field named byname.responseHdrName(int index)Returns the field name of the response header at zero-based indexindex.responseHdrValue(int index)Returns the field value of the response header at zero-based indexindex.voidSends a request whose binary body is read from theBinDatainbody.voidsendReqFormUrlEncoded(String httpVerb, String uriPath)Sends anapplication/x-www-form-urlencodedrequest.voidsendReqMultipart(String httpVerb, String uriPath)Sends a multipart request using the parts configured with,getPartSelector(), and the multipart-body methods.addHeader(String, String)voidsendReqNoBody(String httpVerb, String uriPath)Sends a request without a request body.voidsendReqSb(String httpVerb, String uriPath, StringBuilder bodySb)Sends a request whose text body is read from theStringBuilderinbodySb.voidsendReqStreamBody(String httpVerb, String uriPath, Stream stream)Sends a request whose body is read from theStreaminstream.voidsendReqStringBody(String httpVerb, String uriPath, String bodyText)Sends a request whose text body is supplied inbodyText, such as JSON, XML, form-independent text, or another textual representation.voidsetAllowHeaderFolding(boolean value)Sets theAllowHeaderFoldingproperty; seegetAllowHeaderFolding().voidsetAllowHeaderQB(boolean value)Sets theAllowHeaderQBproperty; seegetAllowHeaderQB().voidsetAuthAws(AuthAws authProvider)Associates theAuthAwsprovider inauthProviderwith this REST object.voidsetAuthAzureSas(AuthAzureSAS authProvider)Associates theAuthAzureSASprovider inauthProviderwith this REST object.voidsetAuthAzureStorage(AuthAzureStorage authProvider)Associates theAuthAzureStorageprovider inauthProviderwith this REST object.voidsetAuthBasic(String username, String password)Configures HTTP Basic authentication usingusernameas the username andpasswordas the password.voidsetAuthBasicSecure(SecureString username, SecureString password)Configures HTTP Basic authentication using theSecureStringobjects inusernameandpasswordfor the username and password.voidsetAuthGoogle(AuthGoogle authProvider)Associates theAuthGoogleprovider inauthProviderwith this REST object.voidsetAuthOAuth1(OAuth1 authProvider, boolean useQueryParams)Associates theOAuth1provider inauthProviderwith this REST object for OAuth 1.0 or OAuth 1.0a request signing.voidsetAuthOAuth2(OAuth2 authProvider)Associates theOAuth2provider inauthProviderwith this REST object.voidsetAuthorization(String value)Sets theAuthorizationproperty; seegetAuthorization().voidsetConnectTimeoutMs(int value)Sets theConnectTimeoutMsproperty; seegetConnectTimeoutMs().voidsetDebugMode(boolean value)Sets theDebugModeproperty; seegetDebugMode().voidsetEnableSecrets(boolean value)Sets theEnableSecretsproperty; seegetEnableSecrets().voidsetHeartbeatMs(int value)Sets theHeartbeatMsproperty; seegetHeartbeatMs().voidSets theHostproperty; seegetHost().voidsetIdleTimeoutMs(int value)Sets theIdleTimeoutMsproperty; seegetIdleTimeoutMs().voidsetMultipartBodyBd(BinData bodyData)Sets the binary body of the multipart part identified byfrom thegetPartSelector()BinDatainbodyData.voidsetMultipartBodySb(StringBuilder bodySb)Sets the text body of the multipart part identified byfrom thegetPartSelector()StringBuilderinbodySb.voidsetMultipartBodyStream(Stream stream)Uses theStreaminstreamas the body source for the multipart part identified by.getPartSelector()voidsetMultipartBodyString(String bodyText)Sets the text body of the multipart part identified bytogetPartSelector()bodyText.voidsetPartSelector(String value)Sets thePartSelectorproperty; seegetPartSelector().voidsetPercentDoneOnSend(boolean value)Sets thePercentDoneOnSendproperty; seegetPercentDoneOnSend().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.voidsetResponseBodyStream(int expectedStatus, boolean autoSetStreamCharset, Stream responseStream)Configures aStreamdestination for response bodies received by the full-request convenience methods.voidsetStreamNonChunked(boolean value)Sets theStreamNonChunkedproperty; seegetStreamNonChunked().voidsetUncommonOptions(String value)Sets theUncommonOptionsproperty; seegetUncommonOptions().voiduseConnection(Socket connection, boolean autoReconnect)Uses the already-connectedSocketinconnectionas the transport for REST requests.Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
Rest
public Rest()Creates a newRestobject.
-
-
Method Details
-
getAllowHeaderFolding
public boolean getAllowHeaderFolding()Controls whether long request-header fields may be folded onto continuation lines. The default isfalse. When set tofalse, each request header is emitted on a single physical line.Modern HTTP compatibility: Obsolete HTTP line folding is rejected by some servers and signing systems. Set this property to
falsewhen the service requires unfolded header lines, as is common for canonicalized request signatures.- Returns:
- the value of the
AllowHeaderFoldingproperty
-
setAllowHeaderFolding
public void setAllowHeaderFolding(boolean value)Sets theAllowHeaderFoldingproperty; seegetAllowHeaderFolding().- Parameters:
value- the new value
-
getAllowHeaderQB
public boolean getAllowHeaderQB()Controls whether non-ASCII request-header values may be converted to RFC 2047 encoded-word form using Q or Base64 encoding. The default istrue.Encoded words have forms such as
=?utf-8?Q?...?=and=?utf-8?B?...?=. When this property isfalse, Chilkat does not apply this conversion.Compatibility feature: RFC 2047 encoded words originated in Internet message headers. Use this behavior only when the target HTTP service expects it; many APIs instead require ASCII header values or a service-specific encoding.
- Returns:
- the value of the
AllowHeaderQBproperty
-
setAllowHeaderQB
public void setAllowHeaderQB(boolean value)Sets theAllowHeaderQBproperty; seegetAllowHeaderQB().- Parameters:
value- the new value
-
getAuthorization
Gets or sets the value sent in the HTTPAuthorizationrequest header. Supply only the field value, such asBearer eyJ..., not the textAuthorization:.Authentication helpers: For generated authentication, prefer the appropriate
SetAuth*method. A configured authentication provider may generate or replace the Authorization header when the request is sent.Provider precedence: When aSetAuth*provider is active, its generated Authorization header takes precedence over this property and over a manually added Authorization header.clears both the provider and this value; clearing top-level headers also clears this property.clearAuth()- Returns:
- the value of the
Authorizationproperty
-
setAuthorization
Sets theAuthorizationproperty; seegetAuthorization().- Parameters:
value- the new value (notnull)
-
getConnectFailReason
public int getConnectFailReason()Afterfails, returns a code identifying the connection stage or TLS handshake stage that failed.connect(String, int, boolean, boolean)Code Meaning
0Success1Empty hostname2DNS lookup failed3DNS timeout4Aborted by the application5Internal failure6Connection timed out7Connection rejected or otherwise failed99Chilkat is not unlocked or the trial expiredTLS-related codes:
Code Meaning
100TLS internal error101Failed to send ClientHello102Unexpected handshake message103Failed to read ServerHello104No server certificate105Unexpected TLS protocol version106Server certificate verification failed107Unacceptable TLS protocol version109Failed to read handshake messages110Failed to send the client-certificate handshake message111Failed to send ClientKeyExchange112Client certificate private key is inaccessible113Failed to send CertificateVerify114Failed to send ChangeCipherSpec115Failed to send Finished116The server Finished message is invalidDetailed diagnostics: Use the code as a category and inspect
LastErrorTextfor the full failure context.Reset after success: A successfulresets this property toconnect(String, int, boolean, boolean)0. HTTP response properties are separate and are not cleared by a later failed connection attempt.- Returns:
- the value of the
ConnectFailReasonproperty (read-only)
-
getConnectTimeoutMs
public int getConnectTimeoutMs()Gets or sets the maximum number of milliseconds to wait for the remote server to accept the TCP connection. This timeout covers connection establishment, not the later sending or receiving of HTTP data.Related timeout: Use
to control how long an established operation may remain without send or receive progress.getIdleTimeoutMs()The default is
30000milliseconds.- Returns:
- the value of the
ConnectTimeoutMsproperty
-
setConnectTimeoutMs
public void setConnectTimeoutMs(int value)Sets theConnectTimeoutMsproperty; seegetConnectTimeoutMs().- Parameters:
value- the new value
-
getDebugMode
public boolean getDebugMode()Whentrue, calls to theSend*andFullRequest*methods compose the complete request but do not transmit it. Retrieve the generated request with. The default isgetLastDebugRequest(BinData)false.Safe request inspection: This is useful for validating signing, headers, query strings, multipart formatting, and body encoding without contacting the server. The captured request may contain secrets.
In debug mode, a composed full-request call reports a synthetic successful result with
ResponseStatusCodeequal to201,ResponseStatusTextequal toOK, and no actual response header or response body.- Returns:
- the value of the
DebugModeproperty
-
setDebugMode
public void setDebugMode(boolean value)Sets theDebugModeproperty; seegetDebugMode().- Parameters:
value- the new value
-
getEnableSecrets
public boolean getEnableSecrets()Controls automatic resolution of credentials from operating-system secure storage. The default isfalse.When set to
true, supported credential inputs may contain a secret specification beginning with!!instead of a literal secret. Chilkat resolves the specification from Windows Credential Manager on Windows or Apple Keychain on macOS.The specification format is:
!![appName|]service[|domain]|username
For this class, secret specifications apply to the username and password supplied to
.setAuthBasic(String, String)Why use secret resolution: It avoids embedding long-lived credentials directly in source code, configuration files, command lines, or logs. The requested secret must already exist in the platform credential store.
- Returns:
- the value of the
EnableSecretsproperty
-
setEnableSecrets
public void setEnableSecrets(boolean value)Sets theEnableSecretsproperty; seegetEnableSecrets().- Parameters:
value- the new value
-
getHeartbeatMs
public int getHeartbeatMs()Controls the interval, in milliseconds, betweenevent callbacks during supported long-running operations. The default isAbortCheck0, which disables periodic AbortCheck callbacks.Choosing an interval: A smaller value makes cancellation more responsive but causes callbacks more frequently.
- Returns:
- the value of the
HeartbeatMsproperty
-
setHeartbeatMs
public void setHeartbeatMs(int value)Sets theHeartbeatMsproperty; seegetHeartbeatMs().- Parameters:
value- the new value
-
getHost
Gets or sets the value of the HTTPHostrequest header.Usually automatic: For a normal connection, Chilkat derives the Host header from the server established by
orconnect(String, int, boolean, boolean). Set this property explicitly only when the request must present a different virtual-host value.useConnection(Socket, boolean)An explicitly assigned value overrides the generated HTTP
Hostfield, but it does not change the TCP/TLS destination established byorconnect(String, int, boolean, boolean).useConnection(Socket, boolean)- Returns:
- the value of the
Hostproperty
-
setHost
Sets theHostproperty; seegetHost().- Parameters:
value- the new value (notnull)
-
getIdleTimeoutMs
public int getIdleTimeoutMs()Gets or sets the maximum number of milliseconds to wait when a send or receive operation has stopped making progress. The default is30000milliseconds.Not an overall deadline: This is an inactivity timeout. An operation can run longer than this value as long as data continues to be sent or received.
A value of
0disables the inactivity timeout.- Returns:
- the value of the
IdleTimeoutMsproperty
-
setIdleTimeoutMs
public void setIdleTimeoutMs(int value)Sets theIdleTimeoutMsproperty; seegetIdleTimeoutMs().- Parameters:
value- the new value
-
getLastRedirectUrl
Returns the redirect target from the most recently received response. The value comes from the responseLocationheader. If the most recent response was not a redirect or did not contain a Location header, this property is empty.Relative redirects: A Location value may be an absolute URL or a relative reference, depending on the server response.Redirect handling: The value is the response Location field as received.
Restdoes not automatically follow the redirect; send a new request explicitly, reconnecting first if the target host changes.- Returns:
- the value of the
LastRedirectUrlproperty (read-only)
-
getLastRequestHeader
Returns the HTTP header fields from the most recently composed request, excluding the request line. The request line is available separately in.getLastRequestStartLine()Sensitive data: The header block may contain credentials, bearer tokens, cookies, or signatures. Avoid writing it to logs unless sensitive values are redacted.
A failed
does not clear this value. It continues to describe the last request that was composed and sent.connect(String, int, boolean, boolean)- Returns:
- the value of the
LastRequestHeaderproperty (read-only)
-
getLastRequestStartLine
Returns the request line from the most recently composed request. It contains the HTTP method, request target, and HTTP version, for example:GET /v1/items?limit=10 HTTP/1.1
A failed
does not clear this value. It continues to describe the last request that was composed and sent.connect(String, int, boolean, boolean)- Returns:
- the value of the
LastRequestStartLineproperty (read-only)
-
getNumResponseHeaders
public int getNumResponseHeaders()Returns the number of response header field occurrences. Enumerate them with zero-based indexes usingandresponseHdrName(int).responseHdrValue(int)A failed
does not reset this count; it remains the count for the last received HTTP response.connect(String, int, boolean, boolean)- Returns:
- the value of the
NumResponseHeadersproperty (read-only)
-
getPartSelector
Selects the multipart entity or part targeted by multipart-building operations such asAddHeader,RemoveHeader, and theSetMultipartBody*methods.Value Selected target
(empty) The top-level request entity0The top-level request entity1The first multipart subpart2The second multipart subpart1.2The second child within the first subpartMultipart indexes: PartSelector uses one-based part numbers, unlike most Chilkat indexed accessors. Reset it to the empty string before modifying top-level request headers.
The value
0, like the empty string, selects the top-level request entity. A nonnumeric selector is invalid. A body assignment can create a higher-numbered part even when lower-numbered parts do not yet exist.- Returns:
- the value of the
PartSelectorproperty
-
setPartSelector
Sets thePartSelectorproperty; seegetPartSelector().- Parameters:
value- the new value (notnull)
-
getPercentDoneOnSend
public boolean getPercentDoneOnSend()Applies to the full-request methods that both upload a request and download a response. It selects which direction is represented by percent-complete events.false(default): progress refers to receiving the response body.true: progress refers to sending the request body.
A known total is required: Percentage can be calculated only when the total byte count is known. For example, a chunked response may not provide a total response length.
- Returns:
- the value of the
PercentDoneOnSendproperty
-
setPercentDoneOnSend
public void setPercentDoneOnSend(boolean value)Sets thePercentDoneOnSendproperty; seegetPercentDoneOnSend().- Parameters:
value- the new value
-
getResponseHeader
Returns the HTTP response header fields from the most recently received response, excluding the status line.Status line: The numeric status and reason text are available through
andgetResponseStatusCode().getResponseStatusText()Repeated fields remain separate and in received order. The field-name casing is preserved. A failed
does not clear this value; it continues to describe the last received HTTP response.connect(String, int, boolean, boolean)- Returns:
- the value of the
ResponseHeaderproperty (read-only)
-
getResponseStatusCode
public int getResponseStatusCode()Returns the numeric HTTP status code from the most recently received response, such as200,404, or503.HTTP status versus method success: Receiving an HTTP error status such as
400or404is still a completed HTTP exchange. InspectResponseStatusCodeand the response body to determine the API-level result.Last completed exchange: A faileddoes not clear this property. It continues to report the status of the last HTTP response that was actually received.connect(String, int, boolean, boolean)- Returns:
- the value of the
ResponseStatusCodeproperty (read-only)
-
getResponseStatusText
Returns the reason phrase associated with the most recently received HTTP status code, such asOKorNot Found.Reason phrases are informational: Applications should make decisions from the numeric status code. A reason phrase may be empty or may vary by server.Last completed exchange: A failed
does not clear this property; it remains associated with the last received HTTP response.connect(String, int, boolean, boolean)- Returns:
- the value of the
ResponseStatusTextproperty (read-only)
-
getStreamNonChunked
public boolean getStreamNonChunked()Controls whether streaming uploads use aContent-Lengthheader instead of HTTP/1.1 chunked transfer encoding when the total body size is known. The default istrue.When
trueand the stream length can be determined—for example, a file stream—Chilkat sends a non-chunked request. Whenfalse, Chilkat usesTransfer-Encoding: chunked. If the stream length is unknown, chunked transfer may still be required.Server compatibility: Some HTTP servers and signing schemes require Content-Length and do not accept chunked request bodies; others support either form.
- Returns:
- the value of the
StreamNonChunkedproperty
-
setStreamNonChunked
public void setStreamNonChunked(boolean value)Sets theStreamNonChunkedproperty; seegetStreamNonChunked().- Parameters:
value- the new value
-
getUncommonOptions
Provides opt-in compatibility settings for uncommon requirements. The default is the empty string. Supply one or more comma-separated keywords:Keyword Effect
AllowDuplicateQueryParamsAllowsAddQueryParamto append another parameter having the same name instead of replacing the existing one.AllowInsecureBasicAuthAllows Basic authentication over a non-TLS remote connection. By default, Basic authentication is allowed only over TLS, an SSH tunnel, or localhost.DisableTls13Disables TLS 1.3 so negotiation is limited to TLS 1.2 or earlier supported versions.ProtectFromVpnOn Android, attempts to bypass an installed or active VPN for this connection.Use sparingly: Leave this property empty unless a documented interoperability requirement calls for one of these options. In particular, AllowInsecureBasicAuth can expose credentials to network observers.
- Returns:
- the value of the
UncommonOptionsproperty
-
setUncommonOptions
Sets theUncommonOptionsproperty; seegetUncommonOptions().- Parameters:
value- the new value (notnull)
-
addHeader
Adds an HTTP request header usingnameas the field name andvalueas the field value. If a request header with the same name is already present for the selected part, its value is replaced.HTTP header names: Field names are case-insensitive. Pass only the field name in
name—for example,Content-Type—and not the trailing colon. For multipart requests,determines whether the header is added to the top-level request or to a MIME part.getPartSelector()Request headers persist across requests until removed or cleared. Adding the same header again replaces its current value.
Multipart selection: Header operations apply to the entity selected by
. Use an empty selector orgetPartSelector()0for top-level request headers; select a part before adding that part's headers.- Parameters:
name- thenameargument (notnull)value- thevalueargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
addMwsSignature
Computes the Amazon Marketplace Web Service (MWS) request signature using the secret key inmwsSecretKeyand adds or replaces theSignaturequery parameter. Call this after all other MWS request parameters have been added.httpVerbis the HTTP method,uriPathis the MWS resource path, anddomainis the request domain.httpVerbanduriPathshould match the values used by the request-sending method. The method also adds or replaces theTimestampparameter using the current system time.Legacy MWS signing: This method implements Amazon MWS signing and is not a general AWS request signer. For AWS services that use AWS authorization providers, use
.setAuthAws(AuthAws)- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)domain- thedomainargument (notnull)mwsSecretKey- themwsSecretKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
addPathParam
Adds or replaces a path-substitution parameter. Before a request is sent, occurrences ofnamein the supplied request path are replaced byvalue.For example, setting
nametofileIdandvaluetoabc123transforms/drive/v3/files/fileIdinto/drive/v3/files/abc123.Placeholders are application-defined: The placeholder syntax is simply the text stored in
name; braces are not required unless they are part of the placeholder text you choose.Matching is case-sensitive and literal. Every occurrence of
nameis replaced, substitutions are applied in the order they were added, and replacement applies to the entireuriPathstring, including any query portion.Reserved characters: The replacement is not a general path-segment encoder. Spaces are percent-encoded, but reserved URI characters such as
/,?, and#remain delimiters, and existing percent escapes are preserved. Percent-encode reserved characters before calling this method when they are intended to be data.Path substitutions persist across requests until replaced or removed with
.clearAllPathParams()- Parameters:
name- thenameargument (notnull)value- thevalueargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
addQueryParam
Adds or replaces a query-string parameter usingnameas the parameter name andvalueas its value. The stored query parameters are incorporated into the request target when a request is sent.Duplicate parameter names: By default, adding the same name again replaces the existing value. To retain repeated names such as
tag=red&tag=blue, includeAllowDuplicateQueryParamsin.Encoding and lifetime:getUncommonOptions()nameandvalueare unencoded text. Chilkat percent-encodes the parameter name and value when composing the request target. For example, a space becomes%20, a literal plus sign becomes%2B, and a literal percent sign becomes%25. Existing percent escapes supplied to this method are therefore encoded again. Parameters persist across ordinary requests until removed or cleared.Parameter names are case-sensitive. Adding the same exact name again replaces the existing value unless
AllowDuplicateQueryParamsis enabled in.getUncommonOptions()- Parameters:
name- thenameargument (notnull)value- thevalueargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
addQueryParamSb
Adds or replaces a query-string parameter named byname. The parameter value is read from theStringBuilderinvalue.Duplicate parameter names: By default, the same name is replaced. Include
AllowDuplicateQueryParamsinto retain repeated names.Encoding and lifetime:getUncommonOptions()nameand the text invalueare unencoded text. Chilkat percent-encodes the parameter name and value when composing the request target. For example, a space becomes%20, a literal plus sign becomes%2B, and a literal percent sign becomes%25. Existing percent escapes supplied to this method are therefore encoded again. Parameters persist across ordinary requests until removed or cleared.Parameter names are case-sensitive. Adding the same exact name again replaces the existing value unless
AllowDuplicateQueryParamsis enabled in.getUncommonOptions()- Parameters:
name- thenameargument (notnull)value- thevalueargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
addQueryParams
Adds multiple query parameters from the query-string text inqueryString. Use the formfield1=value1&field2=value2&field3=value3.Encoding responsibility: The values in
queryStringmust already be percent-encoded as required for a URL query string. Do not include a leading?. For individual name/value pairs,is usually clearer.addQueryParam(String, String)The input is parsed as an already URL-encoded query string and then normalized when the request is composed. A plus sign is interpreted as a space and is emitted as
%20; encoded delimiters such as%26remain data; an item without an equals sign is treated as a parameter with an empty value.Parameters added by this method persist across ordinary requests. When ARG2 of a request method already contains a query string, those inline parameters appear first, followed by the parameters stored in the
Restobject.- Parameters:
queryString- thequeryStringargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
clearAllHeaders
public void clearAllHeaders()Removes all HTTP request headers previously added to this object.The method clears headers only from the entity selected by
. Clearing top-level headers also clears thegetPartSelector()property. Automatically generated fields such asgetAuthorization()HostandContent-Lengthmay be added again when the next request is composed.- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
clearAllParts
public void clearAllParts()Removes all multipart subparts from the request under construction. This is useful when reusing the same REST object after sending a multipart request.Scope: This clears multipart parts; it does not by itself clear query parameters, path parameters, authentication settings, or ordinary top-level request headers.
This also resets
to the empty string and releases the configured multipart bodies and part streams.getPartSelector()- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
clearAllPathParams
public void clearAllPathParams()Removes all path-substitution parameters previously added with.addPathParam(String, String)After clearing, placeholder text in later request paths is sent unchanged.
- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
clearAllQueryParams
public void clearAllQueryParams()Removes all query parameters previously added to this object.This clears the stored query/form parameter collection. It does not remove a query string written directly in the
uriPathargument of a request method.- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
clearAuth
public void clearAuth()Clears authentication providers and credentials previously configured through this class'sSetAuth*methods.This removes the active authentication provider and clears the manually configured
value.getAuthorization()- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
clearResponseBodyStream
public void clearResponseBodyStream()Clears the response-stream destination previously configured by. Subsequent full-request methods return or store the response body normally instead of streaming it to that destination.setResponseBodyStream(int, boolean, Stream)Clearing the destination does not alter the
Streamobject itself. -
connect
Establishes the initial TCP connection to the REST server.hostnameis a DNS hostname or an IPv4/IPv6 address,portis the server port, andtlsspecifies whether the connection uses TLS. Common combinations are port80withtlsset tofalse, and port443withtlsset totrue.If
autoReconnectistrue, subsequent requests may automatically reconnect when the existing connection is no longer usable. IfautoReconnectisfalse, a lost connection causes the request to fail until the application explicitly reconnects.Hostname only:
hostnameis not a URL. Forhttps://api.example.com/v1/items, passapi.example.com. The request path is supplied separately to the request method.Advanced connections:Connectis intended for a direct connection. For HTTP or SOCKS proxies, SSH tunneling, client certificates, custom socket routing, or other advanced connection setup, establish a connectedSocketand pass it to.Reconnect behavior: WhenuseConnection(Socket, boolean)autoReconnectistrue, Chilkat can establish a new connection before a later request after the previous connection has closed. This option should not be interpreted as a promise to replay a request that failed after transmission began.Result-state behavior: A successful connection resetstogetConnectFailReason()0. A failedConnectdoes not clear the HTTP response and last-request properties from an earlier completed exchange; those properties continue to describe the last HTTP request/response, not the failed connection attempt.- Parameters:
hostname- thehostnameargument (notnull)port- theportargumenttls- thetlsargumentautoReconnect- theautoReconnectargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
disconnect
public void disconnect(int maxWaitMs)Closes the current HTTP connection, if one is open.maxWaitMsis the maximum number of milliseconds to wait while attempting a clean shutdown.Tunneled connections: When the REST connection uses an SSH tunnel, this closes the logical channel used by REST. It does not close the underlying SSH session itself.Socket supplied by UseConnection: When the transport was supplied through
, callinguseConnection(Socket, boolean)Disconnectalso disconnects thatSocket. If automatic reconnection was enabled, a later request may reconnect it.- Parameters:
maxWaitMs- themaxWaitMsargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fullRequestBd
public void fullRequestBd(String httpVerb, String uriPath, BinData binData, StringBuilder responseBody)Sends a complete request whose binary body is read from theBinDatainbinData. The text response body replaces the existing contents of theStringBuilderinresponseBody.Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).HTTP status versus method success: Receiving an HTTP error status such asuseConnection(Socket, boolean)400or404is still a completed HTTP exchange. Inspectand the response body to determine the API-level result.getResponseStatusCode()responseBodyis cleared and replaced with the textual response body.- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)binData- thebinDataargument (notnull)responseBody- theresponseBodyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fullRequestFormUrlEncoded
Sends a completeapplication/x-www-form-urlencodedrequest. The form body is built from the parameters previously added withoraddQueryParam(String, String). The request Content-Type is set toaddQueryParams(String)application/x-www-form-urlencoded. The response body is read as text and returned.This convenience method performs the equivalent of
,sendReqFormUrlEncoded(String, String), andreadResponseHeader()in sequence.readRespBodyString()For full-request methods,
selects whether percent-complete events refer to sending the request body or receiving the response body.getPercentDoneOnSend()Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).HTTP status versus method success: Receiving an HTTP error status such asuseConnection(Socket, boolean)400or404is still a completed HTTP exchange. Inspectand the response body to determine the API-level result.getResponseStatusCode()Parameters written directly in
uriPathremain in the URL query string. Parameters stored through,addQueryParam(String, String), oraddQueryParamSb(String, StringBuilder)are encoded into the form body. After the form request is sent, this stored parameter collection is cleared.addQueryParams(String)Persistent Content-Type: The method sets the top-level
Content-Typetoapplication/x-www-form-urlencoded. That request-header value remains configured for later requests until it is replaced or cleared.- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fullRequestMultipart
Sends a complete multipart request using the parts and part headers configured through,getPartSelector(), and the multipart-body methods. The response body is read as text and returned.addHeader(String, String)This convenience method performs the equivalent of
,sendReqMultipart(String, String), andreadResponseHeader()in sequence.readRespBodyString()For full-request methods,
selects whether percent-complete events refer to sending the request body or receiving the response body.getPercentDoneOnSend()Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).HTTP status versus method success: Receiving an HTTP error status such asuseConnection(Socket, boolean)400or404is still a completed HTTP exchange. Inspectand the response body to determine the API-level result.Multipart state: Assigning a body to a selected part creates that part. Parts may be created out of numeric order, persist across multipart requests, and retain the generated boundary while the multipart structure remains configured. The default top-level media type isgetResponseStatusCode()multipart/form-data.The request fails if no multipart subparts are configured.
- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fullRequestNoBody
Sends a complete request with no request body. The response body is read as text and returned.This convenience method performs the equivalent of
,sendReqNoBody(String, String), andreadResponseHeader()in sequence.readRespBodyString()Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).HTTP status versus method success: Receiving an HTTP error status such asuseConnection(Socket, boolean)400or404is still a completed HTTP exchange. Inspectand the response body to determine the API-level result.getResponseStatusCode()- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fullRequestNoBodyBd
Sends a complete request without a request body and stores the binary response body in theBinDatainbinData, replacing its previous contents.Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).HTTP status versus method success: Receiving an HTTP error status such asuseConnection(Socket, boolean)400or404is still a completed HTTP exchange. Inspectand the response body to determine the API-level result.getResponseStatusCode()binDatais cleared and replaced with the binary response body.- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)binData- thebinDataargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fullRequestNoBodySb
Sends a complete request without a request body and stores the text response body in theStringBuilderinsb, replacing its previous contents.This is the
StringBuilderform of.fullRequestNoBody(String, String)Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).HTTP status versus method success: Receiving an HTTP error status such asuseConnection(Socket, boolean)400or404is still a completed HTTP exchange. Inspectand the response body to determine the API-level result.getResponseStatusCode()sbis cleared and replaced with the textual response body.- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)sb- thesbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fullRequestSb
public void fullRequestSb(String httpVerb, String uriPath, StringBuilder requestBody, StringBuilder responseBody)Sends a complete request whose text body is read from theStringBuilderinrequestBody. The text response body replaces the existing contents of theStringBuilderinresponseBody.This is the
StringBuilderform of.fullRequestString(String, String, String)Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).HTTP status versus method success: Receiving an HTTP error status such asuseConnection(Socket, boolean)400or404is still a completed HTTP exchange. Inspectand the response body to determine the API-level result.Text encoding and Content-Type: Unicode text is encoded as UTF-8. Generic string-body methods do not automatically add agetResponseStatusCode()Content-Typeheader; add the media type required by the API, such asapplication/json; charset=utf-8.responseBodyis cleared and replaced with the response body.- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)requestBody- therequestBodyargument (notnull)responseBody- theresponseBodyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fullRequestStream
Sends a complete request whose body is read from theStreaminstream. Streaming is appropriate for large uploads because the entire request body need not be held in memory. The response body is read as text and returned.This convenience method performs the equivalent of
,sendReqStreamBody(String, String, Stream), andreadResponseHeader()in sequence.readRespBodyString()For full-request methods,
selects whether percent-complete events refer to sending the request body or receiving the response body.getPercentDoneOnSend()Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).HTTP status versus method success: Receiving an HTTP error status such asuseConnection(Socket, boolean)400or404is still a completed HTTP exchange. Inspectand the response body to determine the API-level result.Stream position: The stream is read from its current position and is left consumed. Reusing the same stream without resetting its source or position sends only the unread remainder, which may be zero bytes.getResponseStatusCode()- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)stream- thestreamargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fullRequestString
Sends a complete request whose text body is supplied inbodyText, such as JSON, XML, or plain text. The response body is read as text and returned.This convenience method performs the equivalent of
,sendReqStringBody(String, String, String), andreadResponseHeader()in sequence.readRespBodyString()For full-request methods,
selects whether percent-complete events refer to sending the request body or receiving the response body.getPercentDoneOnSend()Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).HTTP status versus method success: Receiving an HTTP error status such asuseConnection(Socket, boolean)400or404is still a completed HTTP exchange. Inspectand the response body to determine the API-level result.Text encoding and Content-Type: Unicode text is encoded as UTF-8. Generic string-body methods do not automatically add agetResponseStatusCode()Content-Typeheader; add the media type required by the API, such asapplication/json; charset=utf-8.- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)bodyText- thebodyTextargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getLastDebugRequest
Copies the fully composed HTTP request generated whilewasgetDebugMode()trueinto theBinDatainbd. The captured data includes the request line, headers, and body that would have been sent.Diagnostic use: Debug mode does not transmit the request. Treat captured requests as sensitive because they may contain authorization headers, cookies, tokens, or request-body credentials.
bdis cleared and replaced. The captured bytes are the complete composed HTTP/1.1 request, including chunk framing when a streaming request usesTransfer-Encoding: chunked.- Parameters:
bd- thebdargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getLastJsonData
Copies operation-specific diagnostic or result information from the most recently completed method into theJsonObjectinjson. Many methods do not produce additional JSON details, in which case the object is empty.Read immediately: Call this immediately after the operation of interest because a later method call may replace the stored JSON data.
- Parameters:
json- thejsonargument (notnull)
-
readRespBd
Reads the response body as raw bytes into theBinDatainresponseBody, replacing its previous contents. Call this after.readResponseHeader()Use for binary content: Typical examples include images, archives, PDFs, encrypted data, and arbitrary file downloads.Read once: A response body may be consumed by only one body-reading method. A second attempt fails immediately. Fully consume the body before sending another request on the same connection; otherwise unread bytes can prevent the next response header from being parsed correctly.Responses without a body: Do not call a body-reading method for a
HEADresponse. A204 No Contentresponse is handled as a successful empty body.- Parameters:
responseBody- theresponseBodyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
readRespBodyStream
Reads the response body into theStreamsupplied instream. Call this after.readResponseHeader()If
autoSetStreamCharsetistrueand the response is textual, the stream'sStringCharsetis set from thecharsetparameter in the responseContent-Typeheader when one is present.autoSetStreamCharsethas no effect for binary responses.Large downloads: A stream can write directly to a file or another destination, avoiding the need to buffer the entire response body in memory.Read once: A response body may be consumed by only one body-reading method. A second attempt fails immediately. Fully consume the body before sending another request on the same connection; otherwise unread bytes can prevent the next response header from being parsed correctly.Responses without a body: Do not call a body-reading method for a
HEADresponse. A204 No Contentresponse is handled as a successful empty body.- Parameters:
stream- thestreamargument (notnull)autoSetStreamCharset- theautoSetStreamCharsetargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
readRespBodyString
Reads the response body as text and returns it. Call this only afterhas returned the response status code.readResponseHeader()Text versus binary: Use this method for JSON, XML, HTML, and other textual responses. Use
orreadRespBd(BinData)for binary or very large content.Read once: A response body may be consumed by only one body-reading method. A second attempt fails immediately. Fully consume the body before sending another request on the same connection; otherwise unread bytes can prevent the next response header from being parsed correctly.Responses without a body: Do not call a body-reading method for areadRespBodyStream(Stream, boolean)HEADresponse. A204 No Contentresponse is handled as a successful empty body.- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
readRespChunkBd
Afterhas been called, reads the next chunk of the response body and appends the received bytes to thereadResponseHeader()BinDatainbd. The call waits until at leastminSizebytes are available, unless the response ends first. The final chunk may contain fewer thanminSizebytes, including zero bytes.Return value Meaning
-1The read failed; inspectLastErrorText.0The remaining response bytes were returned and the response body is complete.1A chunk was returned and more response bytes remain.Incremental processing: This method is useful when the application wants to process a long response progressively rather than buffer it all at once.
- Parameters:
minSize- theminSizeargumentbd- thebdargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
readRespSb
Reads the response body as text into theStringBuilderinresponseBody, replacing its previous contents. Call this after.readResponseHeader()Read once: A response body may be consumed by only one body-reading method. A second attempt fails immediately. Fully consume the body before sending another request on the same connection; otherwise unread bytes can prevent the next response header from being parsed correctly.Responses without a body: Do not call a body-reading method for a
HEADresponse. A204 No Contentresponse is handled as a successful empty body.- Parameters:
responseBody- theresponseBodyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
readResponseHeader
public int readResponseHeader()Reads the HTTP response status line and header fields. The returned integer is the HTTP status code, such as200,404, or500. A return value of-1means that no HTTP response was received because a transport or protocol error occurred.After this method returns a status code, inspect
,getResponseHeader(),getResponseStatusCode(), and the response-header access methods. If the response has a body, read it withgetResponseStatusText(),readRespBodyString(),readRespBd(BinData), or another appropriate body-reading method.readRespBodyStream(Stream, boolean)Do not infer body presence from the request method alone: Whether a response body is present depends on the response status, request method, and response headers. For example, a GET commonly has a response body, while HEAD does not.Read once: A response body may be consumed by only one body-reading method. A second attempt fails immediately. Fully consume the body before sending another request on the same connection; otherwise unread bytes can prevent the next response header from being parsed correctly.Responses without a body: Do not call a body-reading method for a
HEADresponse. A204 No Contentresponse is handled as a successful empty body.- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
removeHeader
Removes all request headers named bynamefrom the request level selected by.getPartSelector()Header-name matching is case-insensitive, and all matching occurrences are removed.
- Parameters:
name- thenameargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
removeQueryParam
Removes all query parameters whose name matchesname.Parameter-name matching is case-sensitive. All parameters having the exact name are removed. A
truereturn value indicates that the operation completed successfully; it does not guarantee that a matching parameter existed.- Parameters:
name- thenameargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
responseHdrByName
Returns the value of the response header field named byname. HTTP header field names are case-insensitive.Repeated response headers: When the response can contain repeated fields, use
,getNumResponseHeaders(), andresponseHdrName(int)to enumerate every field occurrence.responseHdrValue(int)If the response contains the same field more than once, this method returns the first matching value. Enumerate the header collection to obtain all occurrences, especially for fields such as
Set-Cookie.- Parameters:
name- thenameargument (notnull)- Returns:
- the result, or
nullif not found (no exception is thrown in that case)
-
responseHdrName
Returns the field name of the response header at zero-based indexindex. Valid indexes range from0throughminus one.getNumResponseHeaders()Enumeration preserves the response-field order and the field-name casing received from the server. Repeated fields occupy separate indexes.
- Parameters:
index- theindexargument- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
responseHdrValue
Returns the field value of the response header at zero-based indexindex. Use the same index withto obtain the corresponding field name.responseHdrName(int)Repeated response fields occupy separate indexes and are returned in received order.
- Parameters:
index- theindexargument- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqBd
Sends a request whose binary body is read from theBinDatainbody.httpVerbis the HTTP method, such asGET,POST, orPUT.uriPathis the request path. This is a low-level send operation: after it succeeds, calland then read the response body with the appropriate response method.readResponseHeader()Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).useConnection(Socket, boolean)- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)body- thebodyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqFormUrlEncoded
Sends anapplication/x-www-form-urlencodedrequest. The request body is built from the parameters added withoraddQueryParam(String, String). Any manually suppliedaddQueryParams(String)Content-Typevalue is replaced withapplication/x-www-form-urlencoded.httpVerbis the HTTP method, such asGET,POST, orPUT.uriPathis the request path. This is a low-level send operation: after it succeeds, calland then read the response body with the appropriate response method.readResponseHeader()Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).useConnection(Socket, boolean)Parameters written directly in
uriPathremain in the URL query string. Parameters stored through,addQueryParam(String, String), oraddQueryParamSb(String, StringBuilder)are encoded into the form body. After the form request is sent, this stored parameter collection is cleared.addQueryParams(String)Persistent Content-Type: The method sets the top-level
Content-Typetoapplication/x-www-form-urlencoded. That request-header value remains configured for later requests until it is replaced or cleared.- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqMultipart
Sends a multipart request using the parts configured with,getPartSelector(), and the multipart-body methods.addHeader(String, String)httpVerbis the HTTP method, such asGET,POST, orPUT.uriPathis the request path. This is a low-level send operation: after it succeeds, calland then read the response body with the appropriate response method.readResponseHeader()Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).Multipart state: Assigning a body to a selected part creates that part. Parts may be created out of numeric order, persist across multipart requests, and retain the generated boundary while the multipart structure remains configured. The default top-level media type isuseConnection(Socket, boolean)multipart/form-data.The request fails if no multipart subparts are configured.
- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqNoBody
Sends a request without a request body.httpVerbis the HTTP method, such asGET,POST, orPUT.uriPathis the request path. This is a low-level send operation: after it succeeds, calland then read the response body with the appropriate response method.readResponseHeader()Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).useConnection(Socket, boolean)- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqSb
Sends a request whose text body is read from theStringBuilderinbodySb. Set the requestContent-Typeheader to identify the body format.httpVerbis the HTTP method, such asGET,POST, orPUT.uriPathis the request path. This is a low-level send operation: after it succeeds, calland then read the response body with the appropriate response method.readResponseHeader()Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).Text encoding and Content-Type: Unicode text is encoded as UTF-8. Generic string-body methods do not automatically add auseConnection(Socket, boolean)Content-Typeheader; add the media type required by the API, such asapplication/json; charset=utf-8.- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)bodySb- thebodySbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqStreamBody
Sends a request whose body is read from theStreaminstream. The stream may supply text or binary data; set the requestContent-Typeheader as required by the API.httpVerbis the HTTP method, such asGET,POST, orPUT.uriPathis the request path. This is a low-level send operation: after it succeeds, calland then read the response body with the appropriate response method.readResponseHeader()Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).Streaming: The stream is consumed while the request is sent, which is useful when the body is too large to hold in memory.Stream position: The stream is read from its current position and is left consumed. Reusing the same stream without resetting its source or position sends only the unread remainder, which may be zero bytes.useConnection(Socket, boolean)- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)stream- thestreamargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sendReqStringBody
Sends a request whose text body is supplied inbodyText, such as JSON, XML, form-independent text, or another textual representation. Set the requestContent-Typeheader to identify the body format expected by the server.httpVerbis the HTTP method, such asGET,POST, orPUT.uriPathis the request path. This is a low-level send operation: after it succeeds, calland then read the response body with the appropriate response method.readResponseHeader()Request path:
uriPathis the path and optional query portion of the URL, not a complete URL. Forhttps://api.example.com/v1/items?limit=10, pass/v1/items?limit=10. The server name and port are established separately byorconnect(String, int, boolean, boolean).Text encoding and Content-Type: Unicode text is encoded as UTF-8. Generic string-body methods do not automatically add auseConnection(Socket, boolean)Content-Typeheader; add the media type required by the API, such asapplication/json; charset=utf-8.- Parameters:
httpVerb- thehttpVerbargument (notnull)uriPath- theuriPathargument (notnull)bodyText- thebodyTextargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAuthAws
Associates theAuthAwsprovider inauthProviderwith this REST object. Chilkat uses the provider to sign each AWS request after the request method, path, query parameters, headers, and body are known. The application does not need to construct theAuthorizationheader manually.Request signing: AWS signatures cover selected request components. Add all required headers and query parameters before sending the request so the generated signature matches the final request.
- Parameters:
authProvider- theauthProviderargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAuthAzureSas
Associates theAuthAzureSASprovider inauthProviderwith this REST object. Chilkat automatically adds anAuthorization: SharedAccessSignature ...header to subsequent requests.SAS terminology: This method is for Azure services that use a Shared Access Signature in the Authorization header. It is distinct from a storage SAS token embedded in a URL query string.
- Parameters:
authProvider- theauthProviderargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAuthAzureStorage
Associates theAuthAzureStorageprovider inauthProviderwith this REST object. Chilkat automatically applies the Azure Storage authorization information required for each request.Azure Storage authentication: The provider contains the storage account credentials and signing settings. Request-specific headers and the resource path are incorporated when the request is sent.
- Parameters:
authProvider- theauthProviderargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAuthBasic
Configures HTTP Basic authentication usingusernameas the username andpasswordas the password. Chilkat automatically generates anAuthorization: Basic ...header for subsequent requests.Security requirement: Basic authentication is an encoding scheme, not encryption. Use it only over TLS. By default, Chilkat blocks Basic authentication on an insecure remote connection;
AllowInsecureBasicAuthinexists only for exceptional compatibility needs.getUncommonOptions()Some APIs use an account ID, client ID, API key, token, or secret in place of a traditional username or password; follow the service documentation.
Authorization precedence: The Basic authentication provider generates the
Authorizationheader when each request is composed and takes precedence over a value set through theproperty orgetAuthorization().addHeader(String, String)- Parameters:
username- theusernameargument (notnull)password- thepasswordargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAuthBasicSecure
Configures HTTP Basic authentication using theSecureStringobjects inusernameandpasswordfor the username and password. The resulting request behavior is the same as.setAuthBasic(String, String)Credential handling:
SecureStringreduces unnecessary exposure of the credential text in ordinary application strings. Basic authentication must still be protected by TLS.Authorization precedence: The Basic authentication provider generates theAuthorizationheader when each request is composed and takes precedence over a manually configured Authorization value.- Parameters:
username- theusernameargument (notnull)password- thepasswordargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAuthGoogle
Associates theAuthGoogleprovider inauthProviderwith this REST object. Chilkat uses the provider to add the Google authentication information needed by subsequent API requests.- Parameters:
authProvider- theauthProviderargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAuthOAuth1
Associates theOAuth1provider inauthProviderwith this REST object for OAuth 1.0 or OAuth 1.0a request signing.If
useQueryParamsistrue, the OAuth parameters and signature are placed in the query string. IfuseQueryParamsisfalse, they are placed in theAuthorizationheader.Final request matters: OAuth 1 signatures depend on the HTTP method, request URL, and parameters. Configure the request completely before sending it.
- Parameters:
authProvider- theauthProviderargument (notnull)useQueryParams- theuseQueryParamsargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setAuthOAuth2
Associates theOAuth2provider inauthProviderwith this REST object. The provider must contain a valid access token. Chilkat then adds anAuthorization: Bearer <access-token>header to each request.The access token may be obtained through an OAuth flow or loaded from previously saved token data. Token acquisition, refresh, expiration, and scope requirements are determined by the authorization server.
Manual bearer headers: A bearer token can also be supplied with
. Do not configure both approaches for the same request because they compete for the sameaddHeader(String, String)Authorizationheader.Provider lifetime: TheOAuth2object is consulted when each request is composed rather than copied at setup time. Keep it alive while theRestobject uses it. Changing itsAccessTokenchanges the bearer token used by subsequent requests.Authorization precedence: The provider-generated bearer header takes precedence over a manually configuredAuthorizationvalue.- Parameters:
authProvider- theauthProviderargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setMultipartBodyBd
Sets the binary body of the multipart part identified byfrom thegetPartSelector()BinDatainbodyData.Setting the body creates the selected part when it does not already exist. Part numbers do not need to be created consecutively.
- Parameters:
bodyData- thebodyDataargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setMultipartBodySb
Sets the text body of the multipart part identified byfrom thegetPartSelector()StringBuilderinbodySb.Setting the body creates the selected part when it does not already exist. Part numbers do not need to be created consecutively.
- Parameters:
bodySb- thebodySbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setMultipartBodyStream
Uses theStreaminstreamas the body source for the multipart part identified by.getPartSelector()Large multipart parts: The stream is read while the request is sent, allowing a large file or generated body to be uploaded without first loading the entire part into memory.Object lifetime and position: The selected part retains the stream as its body source until the multipart request is sent or the parts are cleared. Keep the
Streamobject alive. It is read from its current position and must be reset before reusing it for another upload.Setting the body creates the selected part when it does not already exist. Part numbers do not need to be created consecutively.
- Parameters:
stream- thestreamargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setMultipartBodyString
Sets the text body of the multipart part identified bytogetPartSelector()bodyText.Part metadata: Use
while the part is selected to set itsaddHeader(String, String)Content-Type,Content-Disposition, and other part headers.Setting the body creates the selected part when it does not already exist. Part numbers do not need to be created consecutively.
- Parameters:
bodyText- thebodyTextargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setResponseBodyStream
public void setResponseBodyStream(int expectedStatus, boolean autoSetStreamCharset, Stream responseStream)Configures aStreamdestination for response bodies received by the full-request convenience methods. The body is written toresponseStreamonly when the response status code matchesexpectedStatus.If streaming occurs successfully, a string-returning full-request method returns
OK. If streaming was selected but writing the body fails, it returnsFAIL. If the status code does not matchexpectedStatus, the body is not streamed and remains available as the method's normal response text.If
autoSetStreamCharsetistrueand the response is textual, the destination stream'sStringCharsetis set from the responseContent-Typecharset when available.autoSetStreamCharsetis ignored for binary responses.expectedStatusvalue Status codes that are streamed200Only200-200200through299-210210through219Resetting this behavior: Call
to restore normal response-body handling.clearResponseBodyStream()For Boolean-returning full-request methods, successful streaming returns
true. AStringBuilderresponse output receivesOK; aBinDataresponse output is cleared. If the status does not matchexpectedStatus, the stream is not written and the method returns the response through its normal output.The configuration remains active for later full-request calls until
is called.clearResponseBodyStream()- Parameters:
expectedStatus- theexpectedStatusargumentautoSetStreamCharset- theautoSetStreamCharsetargumentresponseStream- theresponseStreamargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
useConnection
Uses the already-connectedSocketinconnectionas the transport for REST requests. The socket may represent a direct TCP or TLS connection, an HTTP or SOCKS proxy connection, an SSH-tunneled channel, or another connection configured through the Socket API.autoReconnectcontrols automatic reconnection for later requests when the connection is no longer usable.When to use this method: Use
for ordinary direct connections. Useconnect(String, int, boolean, boolean)UseConnectionwhen the connection requires advanced Socket configuration.Socket lifetime: TheRestobject retains and operates on the suppliedSocket. Keep the Socket object alive while it is attached. Callingdisconnects it; withdisconnect(int)autoReconnectset totrue, a later request can reconnect the same Socket object.- Parameters:
connection- theconnectionargument (notnull)autoReconnect- theautoReconnectargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
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
-