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
.
Historique
Release | Modifications |
---|---|
19 R6 | Classe ajoutée |
Exemple
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)
//Méthode onResponse, si vous souhaitez traiter la requête de manière asynchrone
Function onError($request : 4D.HTTPRequest ; $event : Object)
//Méthode onError, si vous souhaitez traiter la requête de manière asynchrone
Vous pouvez maintenant créer votre requête :
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() //Si vous voulez traiter la requête de manière synchrone
//Maintenant vous pouvez utiliser $request.response pour accéder au résultat de la requête ou $request.error pour vérifier l'erreur qui s'est produite.
Objet HTTPRequest
Un objet HTTPRequest est un objet non partageable.
Les objets HTTPRequest fournissent les propriétés et fonctions suivantes :
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()
Historique
Release | Modifications |
---|---|
20 | Validation TLS par défaut |
19 R7 | Support of automaticRedirections and decodeData properties |
4D.HTTPRequest.new( url : Text { ; options : Object } ) : 4D.HTTPRequest
Paramètres | Type | Description | |
---|---|---|---|
url | Text | -> | URL à laquelle envoyer la requête |
options | Object | -> | Propriétés de configuration de la requête |
Résultat | 4D.HTTPRequest | <- | Nouvel objet HTTPRequest |
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. La syntaxe à utiliser est la suivante :
{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.
Par exemple, vous pouvez passer les chaînes suivantes :
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:
Propriété | Type | Description | Par défaut |
---|---|---|---|
automaticRedirections | Boolean | Si true, les redirections sont effectuées automatiquement (jusqu'à 5 redirections sont gérées, la 6e réponse de redirection est renvoyée s'il y en a une) | True |
body | Variant | Body of the request (required in case of post or put requests). Il peut s'agir d'un texte, d'un blob ou d'un objet. Le content-type est déterminé à partir du type de cette propriété, sauf s'il est défini dans les headers | undefined |
certificatesFolder | Folder | Définit le dossier actif des certificats du client | undefined |
dataType | Text | Type de l'attribut response body. Valeurs : "text", "blob", "object", ou "auto". Si "auto", le type du contenu du corps sera déduit de son type MIME (object pour JSON, text pour texte, javascript, xml, message http et url sous forme encodée, blob sinon) | "auto" |
decodeData | Boolean | If true, the data received in the onData callback is uncompressed | False |
encoding | Text | Used only in case of requests with a body (post or put methods). Encodage du body content de la requête s'il s'agit d'un texte, ignoré si le content-type est défini dans les headers | "UTF-8" |
headers | Object | Headers de la requête. Syntax: headers.key=value (value can be a Collection if the same key must appear multiple times) | Objet vide |
method | Text | "POST", "GET", ou autre méthode | "GET" |
minTLSVersion | Text | Sets the minimum version of TLS: "TLSv1_0 ", "TLSv1_1 ", "TLSv1_2 ", "TLSv1_3 " | "TLSv1_2 " |
onData | Function | Callback lorsque les données du body sont reçues. Elle reçoit deux objets en paramètres (voir ci-dessous) | undefined |
onError | Function | Callback lorsqu'une erreur se produit. Elle reçoit deux objets en paramètres (voir ci-dessous) | undefined |
onHeaders | Function | Callback lorsque les headers sont reçus. Elle reçoit deux objets en paramètres (voir ci-dessous) | undefined |
onResponse | Function | Rappel lorsqu'une réponse est reçue. Elle reçoit deux objets en paramètres (voir ci-dessous) | undefined |
onTerminate | Function | Rappel lorsque la requête est terminée. Elle reçoit deux objets en paramètres (voir ci-dessous) | undefined |
protocol | Text | "auto" ou "HTTP1". "auto" signifie HTTP1 dans l'implémentation actuelle | "auto" |
proxyAuthentication | authentication object | Objet manipulant l'authentification du proxy | undefined |
serverAuthentication | authentication object | Objet manipulant l'authentification par serveur | undefined |
returnResponseBody | Boolean | If false, the response body is not returned in the response object. Returns an error if false and onData is undefined | True |
timeout | Real | Timeout en secondes. Undefined = pas de timeout | Undefined |
validateTLSCertificate | Boolean | Si faux, 4D ne valide pas le certificat TLS et ne renvoie pas d'erreur s'il est invalide (c'est-à-dire expiré, auto-signé...). Important : dans l'implémentation actuelle, l'autorité de certification elle-même n'est pas vérifiée. | True |
Fonctions de callback
Toutes les fonctions de callback reçoivent deux paramètres objet:
Paramètres | Type |
---|---|
$param1 | HTTPRequest object |
$param2 | Event object |
Voici la séquence des appels de callbacks :
onHeaders
is always called onceonData
is called zero or several times (not called if the request does not have a body)If no error occured,
onResponse
is always called onceIf an error occurs,
onError
is executed once (and terminates the request)onTerminate
is always executed once
event object
An event
object is returned when a callback function is called. Il contient les propriétés suivantes :
Propriété | Type | Description |
---|---|---|
.data | blob | Données reçues. It is always undefined except in the onData callback |
.type | text | Type d'événement. Valeurs possibles : "response", "error", "headers", "data", or "terminate" |
authentication object
An authentication object handles the options.serverAuthentication
or options.proxyAuthentication
property. Il peut contenir les propriétés suivantes :
Propriété | Type | Description | Par défaut |
---|---|---|---|
name | Text | Nom utilisé pour l'authentification | undefined |
password | Text | Mot de passe utilisé pour l'authentification | undefined |
method | Text | Méthode utilisée pour l'authentification : "basic", "digest", "auto" | "auto" |
HTTP Parse message
Historique
Release | Modifications |
---|---|
20 R4 | Ajout |
HTTP Parse message( data : Text ) : Object
HTTP Parse message( data : Blob ) : Object
Paramètres | Type | Description | |
---|---|---|---|
data | Text, Blob | -> | Données à analyser |
Résultat | Object | <- | Objet dont chaque propriété est une partie des données multiparties |
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.
HTTP lui-même est un protocole de communication sans état. Dans ce cadre, les clients initient la communication en envoyant des messages "request" aux serveurs, en spécifiant des détails tels que la méthode, la cible, les en-têtes, le contenu, etc. Les serveurs, à leur tour, répondent par des messages "response" qui contiennent les mêmes détails. HTTP Parse message
parses either the "request" or the "response" message into a well-organized object.
Exemple
Dans l'exemple suivant, nous analysons les données d'un fichier texte contenant des requêtes HTTP.
Voici le contenu du fichier :
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--
Pour analyser le fichier :
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:
Propriété | Type | Description | |
---|---|---|---|
errors | Collection | Pile d'erreurs 4D en cas d'erreur | |
[].errCode | Number | Code d'erreur 4D | |
[].message | Text | Description de l'erreur 4D | |
[].componentSignature | Text | Signature du composant interne qui a retourné l'erreur |
.headers
headers : Object
Description
The .headers
property contains the headers
passed in the options
object when calling new(). S'il a été omis, contient un objet vide.
.method
method : Text
Description
The .method
property contains the method
passed in the options
object when calling new(). S'il a été omis, elle contient "GET".
.protocol
protocol : Text
Description
The .protocol
property contains the protocol
passed in the options
object when calling new(). S'il a été omis ou si "auto" a été utilisé, contient la version du protocole utilisé.
.response
Historique
Release | Modifications |
---|---|
19 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. Il contient les propriétés suivantes :
Propriété | Type | Description |
---|---|---|
.body | Variant | Body de la réponse. The type of the message is defined according to the dataType property. Undefined si le body n'a pas encore été reçu |
.headers | Object | Headers de la réponse. Les noms des headers sont retournés en minuscules. <headername>.key = value (value can be a collection if the same key appears multiple times). Undefined si les headers n'ont pas encore été reçus. |
.status | Number | Status code de la réponse |
.statusText | Text | Message expliquant le status code |
.rawHeaders | Object | Headers de la réponse. Les noms des headers sont retournés tels quels (avec leur casse d'origine). <headerName>.key = value (value can be a collection if the same key appears multiple times). Undefined si les headers n'ont pas encore été reçus. |
.returnResponseBody
returnResponseBody : Boolean
Description
The .returnResponseBody
property contains the returnResponseBody
passed in the options
object when calling new(). S'il a été omis, il contient True.
.terminate()
.terminate()
Paramètres | Type | Description | |
---|---|---|---|
Ne requiert aucun paramètre |
Description
Cette fonction est 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(). S'il a été omis, il contient Undefined.
.url
url : Text
Description
The .url
property contains the URL of the HTTP request.
.wait()
.wait( { time : Real } ) : HTTPRequestClass
Paramètres | Type | Description | |
---|---|---|---|
time | Real | -> | Délai d'attente maximum en secondes pour la réponse |
Résultat | 4D.HTTPRequest | <- | Objet HTTPRequest |
Description
Cette fonction est 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.
Si la réponse du serveur est déjà arrivée, la fonction rend la main immédiatement.