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
📋 Table of Contents
🚀 Quick Start Examples
Using the http() BIF (Fluent API)
http() BIF (Fluent API)Using the bx:http Component (Template Syntax)
bx:http Component (Template Syntax)🎯 Choosing Your Approach
The http() BIF - Fluent API
http() BIF - Fluent APINew 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
bx:http Component - Template SyntaxThe 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 Signatures
onRequestStart( httpResult, httpClient )
onRequestStart( httpResult, httpClient )Called immediately before the HTTP request is sent to the server.
Parameters:
httpResult(struct) - Partial result structure with request details (URL, method, headers, etc.)httpClient(BoxHttpClient) - The client instance making the request
Use Cases:
Generate and log request IDs for tracing
Validate request configuration before sending
Start timing/monitoring operations
Log request details for debugging
Example:
onChunk( chunk, lastEventId, httpResult, httpClient, response )
onChunk( chunk, lastEventId, httpResult, httpClient, response )Called for each chunk of data received from the server. Essential for streaming and SSE consumption.
Parameters:
chunk(any) - The data chunk received:Regular HTTP: String or binary data chunk
SSE mode: Struct with
{ data, event, id, retry }fields
lastEventId(string) - Most recent SSE event ID (for reconnection support)httpResult(struct) - The result structure (partially populated during streaming)httpClient(BoxHttpClient) - The client instanceresponse(java.net.http.HttpResponse) - Raw Java HTTP response object
Use Cases:
Process streaming API responses (OpenAI, Claude, etc.)
Consume Server-Sent Events from remote servers
Monitor download progress
Process large responses incrementally without loading into memory
Example (Streaming JSON):
Example (SSE Consumption):
onComplete( httpResult )
onComplete( httpResult )Called after the HTTP request completes successfully.
Parameters:
httpResult(struct) - Complete result structure with all response data
Use Cases:
Final cleanup operations
Success logging and metrics
Trigger downstream processes
Send completion notifications
Example:
onError( error, httpResult )
onError( error, httpResult )Called when an error occurs during the HTTP request.
Parameters:
error(Exception) - The error/exception that occurredhttpResult(struct) - Partial result structure (may contain partial data)
Use Cases:
Implement retry logic with exponential backoff
Log errors with context
Send error notifications/alerts
Graceful degradation and fallback handling
Example:
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)
http() BIF (Fluent API)With bx:http Component
bx:http ComponentReal-World Callback Patterns
Pattern 1: Progress Tracking
Pattern 2: Request/Response Logging
Pattern 3: Retry with Circuit Breaker
Callback Best Practices:
Keep callbacks lightweight - Avoid heavy processing in
onChunkto prevent blockingUse try-catch - Protect against errors in callback code
Store context carefully - Use closure variables or pass context through httpResult
Log appropriately - Use different log levels (DEBUG for chunks, INFO for completion, ERROR for failures)
Handle SSE disconnects - Implement reconnection logic in
onErrorfor SSE streamsMonitor memory - Process and discard data incrementally in
onChunkfor large responsesUse request IDs - Generate IDs in
onRequestStartfor correlation across callbacksImplement timeouts - Don't rely solely on callbacks for timeout handling
📊 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:
🔐 Client Certificates
BoxLang supports mutual TLS authentication using client certificates. This allows your application to authenticate to servers that require client-side SSL/TLS certificates, commonly used in enterprise environments and B2B integrations.
🔹 Basic Client Certificate Authentication
🔹 Supported Certificate Formats
BoxLang supports PKCS#12 (.p12 or .pfx) certificate files, which bundle the client certificate and private key in a single encrypted file.
🔹 Common Use Cases
Enterprise API Integration:
B2B Partner Integration:
Government/Regulated APIs:
🔹 Security Best Practices
Certificate Security Guidelines:
Never hardcode passwords - Use environment variables or encrypted configuration
Restrict file permissions - Ensure certificate files are readable only by the application user
Rotate certificates - Regularly update certificates before expiration
Use secure storage - Store certificates in protected directories outside web root
Monitor expiration - Set up alerts for certificate expiration dates
🔹 Error Handling
🔹 Troubleshooting
Common Issues:
"Certificate password incorrect"
Verify the password matches the certificate file
"Certificate not found"
Check file path is absolute and file exists
"Certificate expired"
Renew and replace the certificate file
"Certificate format not supported"
Ensure certificate is in PKCS#12 (.p12/.pfx) format
"SSL handshake failed"
Verify server trusts your certificate's CA
📦 Binary Responses
Control how binary content is handled:
🎯 Advanced Examples
🔹 RESTful API CRUD Operations
🔹 GraphQL Query
🔹 Handling Cookies
🔹 Custom User Agent
🔹 Request with Multiple Headers
🚀 The http() BIF - Fluent API Reference
http() BIF - Fluent API ReferenceNew in BoxLang 1.8.0 - The http() BIF provides a modern, fluent API for building and executing HTTP requests programmatically.
Basic Syntax
HTTP Method Shortcuts
The BIF provides convenient method shortcuts:
Configuration Methods
Request Configuration
Headers and Parameters
Request Body
File Uploads
File Downloads
Authentication
Response Transformers
Transform the response automatically before returning:
Conditional Building
Build requests conditionally:
Streaming and Callbacks
New in BoxLang 1.8.0 - Stream responses with callbacks:
Server-Sent Events (SSE) Consumption
New in BoxLang 1.8.0 - Consume SSE streams:
Request Inspection
Debug your request before sending:
Error Handling
📡 Server-Sent Events (SSE) Consumption
New in BoxLang 1.8.0 - Both the http() BIF and bx:http component support consuming Server-Sent Events (SSE) streams from remote servers.
What is SSE Consumption?
While the SSE() BIF creates SSE streams (server-to-client), SSE consumption allows you to connect to existing SSE endpoints and process events as they arrive. This is perfect for:
🤖 Consuming AI streaming APIs (OpenAI, Claude, etc.)
📊 Real-time dashboard data feeds
🔔 Event notifications from third-party services
📈 Live metrics and monitoring streams
🔄 Real-time updates from microservices
Using the http() BIF for SSE
http() BIF for SSEUsing the bx:http Component for SSE
bx:http Component for SSEReal-World SSE Examples
OpenAI Streaming Chat
Live Dashboard Metrics
Real-Time Notifications
SSE Event Structure
Each SSE event received in the onChunk callback contains:
SSE Callback Parameters
The onChunk callback for SSE receives:
event
struct
The SSE event structure (data, event, id, retry)
lastEventId
string
The most recent event ID received (for reconnection)
httpResult
struct
The HTTP result structure
httpClient
object
The BoxHttpClient instance
response
object
The raw Java HttpResponse object
SSE Best Practices
Best Practices:
Always handle errors - Network issues can interrupt streams
Store
lastEventId- Use it to reconnect and resume from last eventParse event types - Different event types may need different handling
Handle
[DONE]signals - Many APIs use this to indicate stream endSet appropriate timeouts - SSE streams can be long-lived
Flush output immediately - For real-time display to end users
Use try-catch - JSON parsing of event data can fail
Important Considerations:
SSE connections are unidirectional (server → client)
Network interruptions will terminate the stream
Use
lastEventIdto resume from where you left offSome proxies/firewalls may interfere with long-lived connections
Set appropriate timeouts for long-running streams
Memory usage grows with accumulated data - process and discard chunks promptly
🎪 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
🔍 Troubleshooting
Common Issues
Issue: Connection timeout
Issue: SSL certificate errors
Issue: Large file uploads timing out
Issue: URL parameters not encoded properly
🎓 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?
