Saltar al contenido principal
Versión: 20 R5 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.

Historia
LanzamientoModificaciones
19 R6Clase añadida

Ejemplo

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)
// Mi método onResponse, si quiere manejar la petición de forma asíncrona

Function onError($request : 4D.HTTPRequest; $event : Object)
// Mi método onError, si quiere manejar la petición de forma asíncrona

Ahora puede crear su petición:

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 desea gestionar la solicitud de forma sincrónica
// Ahora puede utilizar $request.response para acceder al resultado de la petición o $request.error para comprobar el error que se ha producido.

Objeto HTTPRequest

Un objeto HTTPRequest es un objeto no compartible.

Los objetos HTTPRequest ofrecen las siguientes propiedades y funciones:

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()

Historia
LanzamientoModificaciones
20Validación TLS por defecto
19 R7Support of automaticRedirections and decodeData properties

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

ParámetrosTipoDescripción
urlText->URL a la que enviar la solicitud
optionsObject->Propiedades de configuración de la petición
Result4D.HTTPRequest<-Nuevo objeto HTTPRequest

Descripción

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 sintaxis a utilizar es:

{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.

Por ejemplo, puede pasar las siguientes cadenas:

    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:

PropiedadTipoDescripciónPor defecto
automaticRedirectionsBooleanSi es true, las redirecciones se realizan automáticamente (se gestionan hasta 5 redirecciones, se devuelve la 6ª respuesta de redirección si la hay)True
bodyVariantBody of the request (required in case of post or put requests). Puede ser un texto, un blob, o un objeto. El content-type se determina a partir del tipo de esta propiedad a menos que se defina dentro de los encabezadosindefinido
certificatesFolderFolderDefine la carpeta de certificados de cliente activaindefinido
dataTypeTextTipo de atributo del cuerpo de la respuesta. Valores: "text", "blob", "object", o "auto". Si "auto", el tipo de contenido del cuerpo se deducirá de su tipo MIME (object para JSON, texto para texto, javascript, xml, mensaje http y formulario codificado en url, blob en caso contrario)"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). Codificación del contenido del cuerpo de la petición si es un texto, se ignora si se define content-type dentro de los encabezados"UTF-8"
headersObjectEncabezados de la petición. Syntax: headers.key=value (value can be a Collection if the same key must appear multiple times)Objeto vacío
methodText"POST", "GET" u otro método"GET"
minTLSVersionTextSets the minimum version of TLS: "TLSv1_0", "TLSv1_1", "TLSv1_2", "TLSv1_3""TLSv1_2"
onDataFunctionRetrollamada cuando se reciben los datos del cuerpo. Recibe dos objetos como parámetros (ver más abajo)indefinido
onErrorFunctionRetrollamada cuando ocurre un error. Recibe dos objetos como parámetros (ver más abajo)indefinido
onHeadersFunctionRetrollamada cuando se reciben los encabezados. Recibe dos objetos como parámetros (ver más abajo)indefinido
onResponseFunctionRetrollamada cuando se recibe una respuesta. Recibe dos objetos como parámetros (ver más abajo)indefinido
onTerminateFunctionRetrollamada cuando la petición haya terminado. Recibe dos objetos como parámetros (ver más abajo)indefinido
protocolText"auto" o "HTTP1". "auto" significa HTTP1 en la implementación actual"auto"
proxyAuthenticationauthentication objectAutenticación del proxy de gestión de objetosindefinido
serverAuthenticationauthentication objectAutenticación del servidor de gestión de objetosindefinido
returnResponseBodyBooleanIf false, the response body is not returned in the response object. Returns an error if false and onData is undefinedTrue
timeoutRealTiempo de espera en segundos. Indefinido = sin tiempo de esperaIndefinido
validateTLSCertificateBooleanSi false, 4D no valida el certificado TLS y no devuelve un error si no es válido (es decir, caducado, autofirmado...). Importante: en la implementación actual, la propia Autoridad de Certificación no se verifica.True

Función callback (retrollamada)

Todas las funciones de retrollamada reciben dos parámetros objeto:

ParámetrosTipo
$param1HTTPRequest object
$param2Event object

Esta es la secuencia de llamadas de retorno:

  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

objeto evento

An event object is returned when a callback function is called. Contiene las siguientes propiedades:

PropiedadTipoDescripción
.datablobDatos recibidos. It is always undefined except in the onData callback
.typetextTipo de evento. Valores posibles: "response", "error", "headers", "data", o "terminate

authentication object

An authentication object handles the options.serverAuthentication or options.proxyAuthentication property. Puede contener las siguientes propiedades:

PropiedadTipoDescripciónPor defecto
nameTextNombre usado para la autenticaciónindefinido
contraseñaTextContraseña utilizada para la autenticaciónindefinido
methodTextMétodo utilizado para la autenticación: "basic", "digest", "auto""auto"

HTTP Parse message

Historia
LanzamientoModificaciones
20 R4Añadidos

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

ParámetrosTipoDescripción
dataText, Blob->Datos a analizar
ResultObject<-Objeto, cada propiedad es parte de los datos de varias partes

Descripción

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

El propio HTTP es un protocolo de comunicación sin estado. En este marco, los clientes inician la comunicación enviando mensajes de "petición" a los servidores, especificando detalles como el método, el objetivo, los encabezados, el contenido, etc. Los servidores, a su vez, responden con mensajes de "respuesta" que incluyen los mismos detalles. HTTP Parse message parses either the "request" or the "response" message into a well-organized object.

Ejemplo

En el siguiente ejemplo, analizamos los datos de un archivo de texto que contiene peticiones HTTP.

Este es el contenido del archivo:

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--

Para analizar el archivo:

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

Descripción

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

.encoding

encoding : Text

Descripción

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

.errors

errors : Collection

Descripción

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:

PropiedadTipoDescripción
errorsCollectionPila de error 4D en caso de error
[].errCodeNumberCódigo de error 4D
[].messageTextDescripción del error 4D
[].componentSignatureTextFirma del componente interno que ha devuelto el error

.headers

headers : Object

Descripción

The .headers property contains the headers passed in the options object when calling new(). Si se omite, contiene un objeto vacío.

.method

method : Text

Descripción

The .method property contains the method passed in the options object when calling new(). .

.protocol

protocol : Text

Descripción

The .protocol property contains the protocol passed in the options object when calling new(). Si se ha omitido o si se ha utilizado "auto", contiene la versión del protocolo utilizada.

.response

Historia
LanzamientoModificaciones
19 R8.headers returns lowercase names. New .rawHeaders property

response : Object

Descripción

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. Ofrece las siguientes propiedades:

PropiedadTipoDescripción
.bodyVariantCuerpo de la respuesta. The type of the message is defined according to the dataType property. Indefinido si el cuerpo no se ha recibido todavía
.headersObjectEncabezados de la respuesta. Los nombres de los encabezados se devuelven en minúsculas. <headername>.key = value (value can be a collection if the same key appears multiple times). Indefinido si el los encabezados no se ha recibido aún.
.statusNumberCódigo de estado de la respuesta
.statusTextTextMensaje explicando el código de estado
.rawHeadersObjectEncabezados de la respuesta. Los nombres de los encabezadoss se devuelven intactos (con sus mayúsculas y minúsculas originales). <headerName>.key = value (value can be a collection if the same key appears multiple times). Indefinido si el los encabezados no se ha recibido aún.

.returnResponseBody

returnResponseBody : Boolean

Descripción

The .returnResponseBody property contains the returnResponseBody passed in the options object when calling new(). Si se omite, contiene True.

.terminate()

.terminate()

ParámetrosTipoDescripción
No requiere ningún parámetro

Descripción

Esta función es hilo seguro.

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

.terminated

terminated : Boolean

Descripción

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

.timeout

timeout : Real

Descripción

The .timeout property contains the timeout passed in the options object when calling new(). .

.url

url : Text

Descripción

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

.wait()

.wait( { time : Real } ) : HTTPRequestClass

ParámetrosTipoDescripción
timeReal->Tiempo máximo en segundos para esperar la respuesta
Result4D.HTTPRequest<-Objeto HTTPRequest

Descripción

Esta función es hilo seguro.

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 respuesta del servidor ya ha llegado, la función regresa inmediatamente.