Skip to main content
Version: v19 R8 BETA

HTTPRequest

Histórico
VersãoMudanças
v19 R6Class added

A classe HTTPRequest permite-lhe tratar objectos HTTPRequest que podem ser utilizados para configurar e enviar pedidos para um servidor HTTP, bem como para processar as respostas do servidor HTTP.

A classe HTTPRequest está disponível a partir da loja de classes 4D . Você cria e envia pedidos HTTP usando a função 4D.HTTPRequest.new() , que retorna um objecto HTTPRequest ``.

Exemplo

Criar uma classe MyHttpRequestOptions para as opções de pedido:

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étodo My onResponse, se quiser manejar a petição de forma assincronica

Function onError($request : 4D.HTTPRequest; $event : Object)
//Método My onError, se quiser manejar a petição de forma assincrônica

Pode agora criar o seu pedido:

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 pode usar $request.response para aceder ao resultado do pedido ou $request.error para verificar o erro que aconteceu.

Objeto HTTPRequest

Um objecto HTTPRequest é um objecto não partilhável.

Os objectos HTTPRequest fornecem as seguintes propriedades e funções:

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

Histórico
VersãoMudanças
v19 R7Support of decodeData property

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

ParâmetrosTipoDescrição
urlText->URL para onde enviar o pedido
optionsObjeto->Pedir propriedades de configuração
Resultados4D.HTTPRequest<-Novo objecto HTTPRequest

|

Descrição

A função 4D.HTTPRequest.new() creates and sends a HTTP request to the HTTP server defined in url with the defined options, and returns a 4D.HTTPRequest object.

O objeto devolvido HTTPRequest é utilizado para processar respostas do servidor HTTP e métodos de chamada.

Em url, passe o URL para onde pretende enviar o pedido. A sintaxe a utilizar é:

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

Se omitir a parte do protocolo (http:// ou https://), é enviado um pedido https.

Por exemplo, pode passar as seguintes cordas:

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

parâmetro options

No parâmetro opções , passe um objeto que possa conter as seguintes propriedades:

PropriedadeTipoDescriçãoPredefinição
bodyVariantCorpo do pedido (requerido no caso de post ou put requests). Pode ser um texto, um blob, ou um objecto. O tipo de conteúdo é determinado a partir do tipo desta propriedade, a menos que seja colocado dentro dos cabeçalhosindefinido
certificatesFolderFolderSets the active client certificates folderindefinido
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"
decodeDataBooleanoIf 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"
headersObjetoHeaders 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)indefinido
onErrorFunctionCallback when an error occurs. It receives two objects as parameters (see below)indefinido
onHeadersFunctionCallback when the headers are received. It receives two objects as parameters (see below)indefinido
onResponseFunctionCallback when a response is received. It receives two objects as parameters (see below)indefinido
onTerminateFunctionCallback when the request is over. It receives two objects as parameters (see below)indefinido
protocolText"auto" ou "HTTP1". "auto" means HTTP1 in the current implementation"auto"
proxyAuthenticationauthentication objectObject handling proxy authenticationindefinido
serverAuthenticationauthentication objectObject handling server authenticationindefinido
returnResponseBodyBooleanoIf false, the response body is not returned in the response object. Returns an error if false and onData is undefinedTrue
timeoutRealTempo de espera em segundos. Undefined = no timeoutIndefinido

Funções Callback

All callback functions receive two object parameters:

ParâmetrosTipo
$param1objeto HTTPRequest
$param2Event objecto

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

objecto evento

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

PropriedadeTipoDescrição
.dadosblobReceived 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:

PropriedadeTipoDescriçãoPredefinição
nameTextName used for authenticationindefinido
senhaTextPassword used for authenticationindefinido
methodTextMethod used for authentication:"basic", "digest", "auto""auto"

.dataType

dataType : Text

Descrição

A propriedade .dataType contém the dataType passed in the options object when calling new(), "auto" if it was omitted.

.encoding

encoding : Text

Descrição

A propriedade .encoding contém the encoding passed in the options object when calling new(), "UTF-8" if it was omitted.

.errors

errors : Collection

Descrição

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:

PropriedadeTipoDescrição
errorsCollection4D error stack in case of error
[].errCodeNúmero4D error code
[].messageTextDescription of the 4D error
[].componentSignatureTextSignature of the internal component which returned the error

.headers

headers : Object

Descrição

A propriedade .headers contém the headers passed in the options object when calling new(). If it was omitted, contains an empty object.

.method

method : Text

Descrição

A propriedade .method contém the method passed in the options object when calling new(). If it was omitted, contains "GET".

.protocol

protocol : Text

Descrição

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

Histórico
VersãoMudanças
v19 R8.headers returns lowercase names. New .rawHeaders property

response : Object

Descrição

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:

PropriedadeTipoDescrição
.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
.headersObjetoHeaders 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.
.estadoNúmeroStatus code of the response
.statusTextTextMessage explaining the status code
.rawHeadersObjetoHeaders 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

Descrição

A propriedade .returnResponseBody contém the returnResponseBody passed in the options object when calling new(). If it was omitted, contains True.

.terminate()

.terminate()

ParâmetrosTipoDescrição
Não exige nenhum parâmetro

|

Descrição

This function is thread-safe.

A função .terminate() aborts the HTTP request. It triggers the onTerminate event.

.terminated

terminated : Boolean

Descrição

A propriedade .terminated contém True if the request is terminated (after the call to onTerminate), false otherwise.

.timeout

timeout : Real

Descrição

A propriedade .timeout contém the timeout passed in the options object when calling new(). If it was omitted, contains Undefined.

.url

url : Text

Descrição

A propriedade .url contém the URL of the HTTP request.

.wait()

.wait( { time : Real } ) : HTTPRequestClass

ParâmetrosTipoDescrição
timeReal->Maximum time in seconds to wait for the response
Resultados4D.HTTPRequest<-HTTPRequest object

|

Descrição

This function is thread-safe.

A função wait() 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.