HTTP/S Calls
Make HTTP/S requests with BoxLang's powerful and flexible HTTP component
BoxLang provides two powerful approaches for making HTTP/S requests: the http() BIF for fluent, programmatic requests and the bx:http component for template-based requests. Both use the same underlying BoxHttpClient, ensuring consistent behavior across your application.
Both approaches provide full support for:
⚡ HTTP/1.1 and HTTP/2 protocols
🔄 All HTTP methods (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, TRACE)
🔒 Authentication (Basic Auth)
📤 File uploads (multipart/form-data)
📥 File downloads
🌐 Proxy server support
🔐 Client certificates (mutual TLS)
⏱️ Configurable timeouts and redirects
📡 Server-Sent Events (SSE) consumption
🎯 Response streaming with callbacks
🚀 Quick Start Examples
Using the http() BIF (Fluent API)
// Simple GET request
result = http( "https://api.example.com/users" )
.send();
// POST with JSON
result = http( "https://api.example.com/users" )
.post()
.jsonBody( '{"name":"John","email":"john@example.com"}' )
.send();
// With query parameters
result = http( "https://api.example.com/users" )
.urlParam( "q", "john" )
.send();Using the bx:http Component (Template Syntax)
🎯 Choosing Your Approach
The http() BIF - Fluent API
New in BoxLang 1.8.0 - The http() BIF provides a modern, fluent interface for building HTTP requests programmatically.
Advantages:
✨ Fluent, chainable API for readable code
🎯 Intellisense-friendly method names
🔧 Programmatic request building
🚀 Built-in response transformers (
asJSON(),asXML(),asText())📡 Native SSE consumption with callbacks
⚡ Async execution with
BoxFutureintegration🎨 Conditional request building with
when(),ifNull(),ifNotNull()
Example:
The bx:http Component - Template Syntax
The bx:http component provides a familiar, tag-based approach for making HTTP requests in templates.
Advantages:
📝 Declarative, template-friendly syntax
🔄 Familiar to CFML developers
📦 Great for view-layer HTTP calls
🎯 Child
bx:httpparamcomponents for parameters📡 SSE consumption with callbacks
🎨 Easy to read and maintain in templates
Example:
🎯 HTTP Request Callbacks Overview
BoxLang provides four powerful callbacks for monitoring and processing HTTP requests in real-time. These callbacks work with both the http() BIF and the bx:http component, enabling you to:
📊 Track request lifecycle events
🌊 Stream and process response data incrementally
📡 Consume Server-Sent Events (SSE) from remote servers
⚠️ Handle errors and implement retry logic
📈 Monitor progress for large uploads/downloads
Callback Reference
onRequestStart
Before the HTTP request begins
Logging, request ID generation, pre-request validation
httpResult, httpClient
onChunk
For each chunk of data received
Streaming responses, SSE consumption, progress tracking
chunk, lastEventId, httpResult, httpClient, response
onComplete
After successful request completion
Cleanup, final logging, success notifications
httpResult
onError
When an error occurs
Error handling, retry logic, alerting
error, httpResult
Callback Execution Order
The callbacks execute in this order:
onRequestStart- Before request beginsonChunk- Multiple times during response (if streaming/SSE)onCompleteORonError- After request finishesonCompletefor successful requestsonErrorfor failed requests
Using Callbacks with Both Approaches
With http() BIF (Fluent API)
With bx:http Component
📊 The Result Structure
The result structure will contain the following keys:
statusCode
The HTTP response code (e.g., 200, 404, 500).
statusText
The HTTP response reason phrase (e.g., "OK", "Not Found", "Internal Server Error").
fileContent
The body of the HTTP response. Usually a string, but could also be a Byte Array depending on the content type and getAsBinary setting.
responseHeader
A structure of response headers. Keys are header names and values are either the header value or an array of values if multiple headers with the same name exist.
header
All the HTTP response headers as a single formatted string.
errorDetail
An error message if the request failed (e.g., connection timeout, unknown host).
mimeType
The MIME type returned in the Content-Type response header.
charset
The character set returned in the Content-Type header (e.g., "UTF-8", "ISO-8859-1").
text
A boolean indicating if the response body is text or binary.
cookies
A query object containing cookies returned by the server with columns: name, value, path, domain, expires, secure, httpOnly, samesite.
HTTP_Version
The HTTP version used for the response (e.g., "HTTP/1.1", "HTTP/2").
requestID
A unique identifier (UUID) for this request, useful for logging and tracing.
userAgent
The User-Agent string that was sent with the request.
executionTime
The time taken to execute the request in milliseconds.
request
A structure containing request details: URL, method, timeout, multipart, headers.
Example Result Structure
⚙️ HTTP Attributes
The HTTP component accepts many attributes to control request behavior. Below are all available attributes:
url
string
required
The HTTP/S endpoint URL to hit. Must start with http:// or https://.
port
numeric
80/443
The port of the endpoint. Defaults to 80 for HTTP and 443 for HTTPS.
method
string
GET
The HTTP method to use: GET, POST, PUT, DELETE, HEAD, TRACE, OPTIONS, PATCH.
username
string
The username for HTTP authentication.
password
string
The password for HTTP authentication.
userAgent
string
BoxLang
The User-Agent header to send with the request.
charset
string
UTF-8
The character encoding to use for the request and response.
resolveUrl
boolean
false
If true, resolves relative URLs in the response body to absolute URLs.
throwOnError
boolean
true
If true, throws an error when the HTTP response status code is 400 or greater.
redirect
boolean
true
If true, follows HTTP redirects (301, 302, etc.).
timeout
numeric
unlimited
The request timeout in seconds. No timeout if not specified.
getAsBinary
string
auto
Controls binary response handling: true/yes (force binary), false/no (force text), auto (detect based on MIME type), never (throw error if binary).
result
string
bxhttp
The name of the variable to store the result structure. If not specified, BoxLang creates a bxHTTP variable in the variables scope. Best practice: Always specify this attribute explicitly.
file
string
The filename for saving the response. If path is not provided, this can be a full file path.
path
string
The directory path where the response file should be saved. If file is not specified, the filename is extracted from the Content-Disposition header.
multipart
boolean
false
If true, sends form fields as multipart/form-data.
multipartType
string
form-data
The multipart content type: form-data or related.
authType
string
BASIC
The authentication type to use: BASIC.
clientCert
string
The path to a client certificate file for SSL/TLS mutual authentication.
clientCertPassword
string
The password for the client certificate.
compression
string
The compression type for the request body.
encodeUrl
boolean
true
If true, encodes the URL. Default is true (encoding enabled).
cachedWithin
string
If set, caches the response for the specified duration (e.g., 10m for 10 minutes, 1h for 1 hour). Returns cached response if available.
proxyServer
string
The proxy server hostname or IP address. Requires proxyPort.
proxyPort
numeric
The proxy server port. Requires proxyServer.
proxyUser
string
The proxy server username for authentication. Requires proxyPassword.
proxyPassword
string
The proxy server password for authentication. Requires proxyUser.
httpVersion
string
HTTP/2
The HTTP protocol version to use: HTTP/1.1 or HTTP/2.
⚡ HTTP/2 Support
BoxLang defaults to HTTP/2 for better performance and efficiency. HTTP/2 provides:
Multiplexed streams over a single connection
Header compression
Server push capabilities
Binary protocol for faster parsing
If you need to use HTTP/1.1 (for compatibility with older servers), set the httpVersion attribute:
When using HTTP/2, the TE header is only supported with the value trailers. If you need to use TE with other values, BoxLang will automatically downgrade to HTTP/1.1.
📝 Result Variable Best Practice
By default, if you don't specify the result attribute, BoxLang will create a variable named bxHTTP in the variables scope to store the HTTP response.
Warning: State Bleeding in Classes
When using the HTTP component inside classes without specifying the result attribute, the bxHTTP variable can bleed into the class's variables scope, potentially causing:
Unintended state persistence across method calls
Memory leaks if the HTTP response is large
Race conditions in concurrent scenarios
Difficult debugging due to implicit variable creation
Always use the result attribute when making HTTP calls inside classes:
📤 HTTPParam Component
The httpparam component allows you to add parameters to HTTP requests in various formats. Parameters can be headers, form fields, URL query strings, cookies, file uploads, or request body content.
Basic Syntax
🔖 Parameter Types
header
Specifies an HTTP header.
No (not encoded)
body
Specifies the request body content.
N/A
xml
Sets Content-Type to text/xml and uses value as the request body.
N/A
cgi
Similar to header but URL encodes the value by default (unless encoded=false).
Yes (by default)
file
Sends the contents of the specified file as part of a multipart request.
N/A
url
Appends a name-value pair to the URL query string. Always URL encoded.
✅ Always
formfield
Sends a form field value. URL encodes by default (unless encoded=false).
Yes (by default)
cookie
Sends a cookie as an HTTP header. URL encodes the value.
Yes (always)
BoxLang 1.6.0 Change: The url param type now always URL encodes values for security and RFC compliance. Previously, encoding could be controlled with the encoded attribute, but as of 1.6.0, URL parameters are always encoded to prevent injection attacks and ensure proper URL formatting.
🔧 HTTPParam Attributes
type
string
required
The parameter type from the available types above.
name
string
conditional
The variable name for the parameter. Required for all types except body, xml, and file.
value
any
conditional
The value of the parameter. Required for all types except file.
file
string
conditional
The absolute path to the file to send. Required when type="file".
encoded
boolean
false
For formfield and cgi types, specifies whether to URL encode the value. Ignored for other types. Note: For url type, encoding is always applied regardless of this setting (as of 1.6.0).
mimetype
string
auto-detected
For file type only. Specifies the MIME type of the file. If not provided, BoxLang attempts to detect it from the file extension.
💡 Common Usage Examples
🔹 Simple GET Request
🔹 POST with JSON Body
🔹 POST with Form Fields
🔹 GET with URL Parameters
URL parameters are always encoded as of BoxLang 1.6.0:
🔹 Custom Headers
🔹 XML Request
🔹 File Upload (Multipart)
🔹 Multiple File Upload
📥 Downloading Files
🔹 Download to Specific Path
🔹 Download Using Content-Disposition
🔹 Download with Full File Path
🔒 Authentication
🔹 Basic Authentication
This automatically adds the Authorization: Basic base64(username:password) header.
🔹 Bearer Token Authentication
🔹 API Key Authentication
🌐 Proxy Server Support
BoxLang supports routing HTTP requests through proxy servers:
🔹 Proxy with Authentication
⏱️ Timeouts and Error Handling
🔹 Setting Timeouts
🔹 Disabling Error Throwing
By default, BoxLang throws an error when the status code is 400 or greater. You can disable this:
🔹 Handling Different HTTP Status Codes
🔄 Redirects
BoxLang automatically follows HTTP redirects (301, 302, etc.) by default:
To disable redirect following:
💾 Response Caching
Cache HTTP responses to improve performance and reduce server load:
📦 Binary Responses
Control how binary content is handled:
🎪 Interceptor Events
BoxLang fires interceptor events during HTTP requests for advanced monitoring and manipulation:
Available Events
onHTTPRequest
Fired before the HTTP request is sent.
requestID, httpClient, httpRequest, targetURI, attributes
onHTTPRawResponse
Fired immediately after receiving the raw response, before processing.
requestID, response, httpClient, httpRequest, targetURI, attributes
onHTTPResponse
Fired after the response is fully processed.
requestID, response, result
Example Interceptor
🎓 Best Practices
Always specify timeouts for external API calls to prevent hanging requests
Use
throwOnError="false"when you need to handle errors gracefullyCache responses when data doesn't change frequently using
cachedWithinUse appropriate HTTP methods - GET for reading, POST for creating, PUT/PATCH for updating, DELETE for removing
Set proper Content-Type headers when sending JSON, XML, or other content types
Handle different status codes - don't assume success, check
statusCodeUse HTTPS for secure communications, especially when sending sensitive data
Leverage HTTP/2 (the default) for better performance
Monitor with interceptors for logging, metrics, and debugging
Use
requestIDfrom the result structure for request tracing and correlation
📚 Related Documentation
File Handling - For working with uploaded/downloaded files
Caching - For understanding response caching strategies
Interceptors - For advanced request/response manipulation
Java Integration - For accessing Java HTTP client directly
With BoxLang's HTTP component, you have a powerful and flexible tool for all your HTTP/S communication needs! 🚀
Last updated
Was this helpful?
