Skip to main content
Version: v20 R4 BETA

HTTPRequest

The HTTPRequest class allows you to handle HTTPRequest objects that can be used to configure and send requests to an HTTP server, as well as to process the HTTP server responses.

The HTTPRequest class is available from the 4D class store. You create and send HTTP requests using the 4D.HTTPRequest.new() function, that returns a HTTPRequest object.

History
VersionChanges
v19 R6Class added

Example

Create a MyHttpRequestOptions class for the request options:

Class constructor($method : Text; $headers : Object; $body : Text)
This.method:=$method
This.headers:=$headers
This.body:=$body

Function onResponse($request : 4D.HTTPRequest; $event : Object)
//My onResponse method, if you want to handle the request asynchronously

Function onError($request : 4D.HTTPRequest; $event : Object)
//My onError method, if you want to handle the request asynchronously

You can now create your request:

var $headers : Object
$headers:=New object()
$headers["field1"]:="value1"

var myHttpRequestOptions : cs.MyHttpRequestOptions
myHttpRequestOptions := cs.MyHttpRequestOptions.new("GET"; $headers; "")

var $request : 4D.HTTPRequest
$request:=4D.HTTPRequest.new("www.google.com"; myHttpRequestOptions)
$request.wait() //If you want to handle the request synchronously
//Now you can use $request.response to access the result of the request or $request.error to check the error that happened.

HTTPRequest Object

An HTTPRequest object is a non-sharable object.

HTTPRequest objects provide the following properties and functions:

dataType : Text    the dataType passed in the options object when calling new(), "auto" if it was omitted
encoding : Text    the encoding passed in the options object when calling new(), "UTF-8" if it was omitted
errors : Collection    the collection of all the errors if at least one error has been triggered
headers : Object    the headers passed in the options object when calling new()
method : Text    the method passed in the options object when calling new()
protocol : Text    the protocol passed in the options object when calling new()
response : Object    the response to the request if it has received at least the status code, undefined otherwise
returnResponseBody : Boolean    the returnResponseBody passed in the options object when calling new()
.terminate()    aborts the HTTP request
terminated : Boolean    True if the request is terminated (after the call to onTerminate), false otherwise
timeout : Real    the timeout passed in the options object when calling new()
url : Text    the URL of the HTTP request
.wait( { time : Real } ) : HTTPRequestClass    waits for the response from the server

4D.HTTPRequest.new()

History
VersionChanges
v20TLS validation by default
v19 R7Support of automaticRedirections and decodeData properties

4D.HTTPRequest.new( url : Text { ; options : Object } ) : 4D.HTTPRequest

ParameterTypeDescription
urlText->URL to which to send the request
optionsObject->Request configuration properties
Result4D.HTTPRequest<-New HTTPRequest object

Description

The 4D.HTTPRequest.new() function creates and sends a HTTP request to the HTTP server defined in url with the defined options, and returns a 4D.HTTPRequest object.

The returned HTTPRequest object is used to process responses from the HTTP server and call methods.

In url, pass the URL where you want to send the request. The syntax to use is:

{http://}[{user}:[{password}]@]host[:{port}][/{path}][?{queryString}]
{https://}[{user}:[{password}]@]host[:{port}][/{path}][?{queryString}]

If you omit the scheme part (http:// or https://), a https request is sent.

For example, you can pass the following strings:

    http://www.myserver.com
www.myserver.com/path
http://www.myserver.com/path?name="jones"
https://www.myserver.com/login
http://123.45.67.89:8083
http://john:smith@123.45.67.89:8083
http://[2001:0db8:0000:0000:0000:ff00:0042:8329]
http://[2001:0db8:0000:0000:0000:ff00:0042:8329]:8080/index.html (**)

options parameter

In the options parameter, pass an object that can contain the following properties:

PropertyTypeDescriptionDefault
automaticRedirectionsBooleanIf true, redirections are performed automatically (up to 5 redirections are handled, the 6th redirection response is returned if any)True
bodyVariantBody of the request (required in case of post or put requests). Can be a text, a blob, or an object. The content-type is determined from the type of this property unless it is set inside the headersundefined
certificatesFolderFolderSets the active client certificates folderundefined
dataTypeTextType of the response body attribute. Values: "text", "blob", "object", or "auto". If "auto", the type of the body content will be deduced from its MIME type (object for JSON, text for text, javascript, xml, http message and url encoded form, blob otherwise)"auto"
decodeDataBooleanIf true, the data received in the onData callback is uncompressedFalse
encodingTextUsed only in case of requests with a body (post or put methods). Encoding of the request body content if it's a text, ignored if content-type is set inside the headers"UTF-8"
headersObjectHeaders of the request. Syntax: headers.key=value (value can be a Collection if the same key must appear multiple times)Empty object
methodText"POST", "GET", or other method"GET"
minTLSVersionTextSets the minimum version of TLS: "TLSv1_0", "TLSv1_1", "TLSv1_2", "TLSv1_3""TLSv1_2"
onDataFunctionCallback when data from the body is received. It receives two objects as parameters (see below)undefined
onErrorFunctionCallback when an error occurs. It receives two objects as parameters (see below)undefined
onHeadersFunctionCallback when the headers are received. It receives two objects as parameters (see below)undefined
onResponseFunctionCallback when a response is received. It receives two objects as parameters (see below)undefined
onTerminateFunctionCallback when the request is over. It receives two objects as parameters (see below)undefined
protocolText"auto" or "HTTP1". "auto" means HTTP1 in the current implementation"auto"
proxyAuthenticationauthentication objectObject handling proxy authenticationundefined
serverAuthenticationauthentication objectObject handling server authenticationundefined
returnResponseBodyBooleanIf false, the response body is not returned in the response object. Returns an error if false and onData is undefinedTrue
timeoutRealTimeout in seconds. Undefined = no timeoutUndefined
validateTLSCertificateBooleanIf false, 4D does not validate the TLS certificate and does not return an error if it is invalid (i.e. expired, self-signed...). Important: In the current implementation, the Certification Authority itself is not verified.True

Callback functions

All callback functions receive two object parameters:

ParameterType
$param1HTTPRequest object
$param2Event object

Here is the sequence of callback calls:

  1. onHeaders is always called once

  2. onData is called zero or several times (not called if the request does not have a body)

  3. If no error occured, onResponse is always called once

  4. If an error occurs, onError is executed once (and terminates the request)

  5. onTerminate is always executed once

event object

An event object is returned when a callback function is called. It contains the following properties:

PropertyTypeDescription
.datablobReceived data. It is always undefined except in the onData callback
.typetextType of event. Possible values: "response", "error", "headers", "data", or "terminate

authentication object

An authentication object handles the options.serverAuthentication or options.proxyAuthentication property. It can contain the following properties:

PropertyTypeDescriptionDefault
nameTextName used for authenticationundefined
passwordTextPassword used for authenticationundefined
methodTextMethod used for authentication:"basic", "digest", "auto""auto"

HTTP Parse message

History
VersionChanges
v20 R4Added

HTTP Parse message( data : Text ) : Object
HTTP Parse message( data : Blob ) : Object

ParameterTypeDescription
dataText, Blob->Data to be parsed
ResultObject<-Object, each property is a part of the multipart data

Description

The HTTP Parse message command parses a multipart/form-data text or blob (HTTP "response" message) and extracts the content to an object. Each property of the returned object corresponds to a part of the multipart data.

info

HTTP itself is a stateless communication protocol. Within this framework, clients initiate communication by sending "request" messages to servers, specifying details like method, target, headers, content, etc. Servers, in turn, respond with "response" messages that include the same details. HTTP Parse message parses either the "request" or the "response" message into a well-organized object.

Example

In the following example, we parse the data from a text file containing HTTP requests.

Here is the content of the file:

POST /batch/gmail/v1/ HTTP/1.1
Accept-Encoding: gzip, deflate
Authorization: Bearer xxxxxx
Connection: Close
Content-Length: 442
Content-Type: multipart/mixed; boundary=batch_19438756D576A14ABA87C112F56B9396; charset=UTF-8
Date: Wed, 29 Nov 2023 13:51:35 GMT
Host: gmail.googleapis.com
User-Agent: 4D/20.4.0


--batch_19438756D576A14ABA87C112F56B9396
Content-Type: application/http
Content-ID: <item1>

GET https://gmail.googleapis.com/gmail/v1/users/me/messages/18c1b58689824c92?format=raw HTTP/1.1


--batch_19438756D576A14ABA87C112F56B9396
Content-Type: application/http
Content-ID: <item2>

GET https://gmail.googleapis.com/gmail/v1/users/me/messages/18c1b58642b28e2b?format=raw HTTP/1.1

--batch_19438756D576A14ABA87C112F56B9396--

To parse the file:

var $message : Text:=File("/RESOURCES/HTTPrequest.txt").getText()
var $parsedMessage : Object:=HTTP Parse message($message)
//$parsedMessage= {
//headers:{"User-Agent":"4D/20.4.0",...},
//parts:[{"contentType":"application/http","contentID":"item1",...}],
//requestLine:"POST /batch/gmail/v1/ HTTP/1.1"
//}

.dataType

dataType : Text

Description

The .dataType property contains the dataType passed in the options object when calling new(), "auto" if it was omitted.

.encoding

encoding : Text

Description

The .encoding property contains the encoding passed in the options object when calling new(), "UTF-8" if it was omitted.

.errors

errors : Collection

Description

The .errors property contains the collection of all the errors if at least one error has been triggered.

Here is the contents of the .errors property:

PropertyTypeDescription
errorsCollection4D error stack in case of error
[].errCodeNumber4D error code
[].messageTextDescription of the 4D error
[].componentSignatureTextSignature of the internal component which returned the error

.headers

headers : Object

Description

The .headers property contains the headers passed in the options object when calling new(). If it was omitted, contains an empty object.

.method

method : Text

Description

The .method property contains the method passed in the options object when calling new(). If it was omitted, contains "GET".

.protocol

protocol : Text

Description

The .protocol property contains the protocol passed in the options object when calling new(). If it was omitted or if "auto" was used, contains the version of the protocol used.

.response

History
VersionChanges
v19 R8.headers returns lowercase names. New .rawHeaders property

response : Object

Description

The .response property contains the response to the request if it has received at least the status code, undefined otherwise.

A response object is a non-sharable object. It provides the following properties:

PropertyTypeDescription
.bodyVariantBody of the response. The type of the message is defined according to the dataType property. Undefined if the body has not been received yet
.headersObjectHeaders of the response. Header names are returned in lowercase. <headername>.key = value (value can be a collection if the same key appears multiple times). Undefined if the headers have not been received yet.
.statusNumberStatus code of the response
.statusTextTextMessage explaining the status code
.rawHeadersObjectHeaders of the response. Header names are returned untouched (with their original case). <headerName>.key = value (value can be a collection if the same key appears multiple times). Undefined if the headers have not been received yet.

.returnResponseBody

returnResponseBody : Boolean

Description

The .returnResponseBody property contains the returnResponseBody passed in the options object when calling new(). If it was omitted, contains True.

.terminate()

.terminate()

ParameterTypeDescription
Does not require any parameters

Description

This function is thread-safe.

The .terminate() function aborts the HTTP request. It triggers the onTerminate event.

.terminated

terminated : Boolean

Description

The .terminated property contains True if the request is terminated (after the call to onTerminate), false otherwise.

.timeout

timeout : Real

Description

The .timeout property contains the timeout passed in the options object when calling new(). If it was omitted, contains Undefined.

.url

url : Text

Description

The .url property contains the URL of the HTTP request.

.wait()

.wait( { time : Real } ) : HTTPRequestClass

ParameterTypeDescription
timeReal->Maximum time in seconds to wait for the response
Result4D.HTTPRequest<-HTTPRequest object

Description

This function is thread-safe.

The wait() function waits for the response from the server.

If a time parameter is passed, the function will wait at most the defined number of seconds.

If the response from the server has already arrived, the function returns immediately.