Saltar para o conteúdo principal
Versão: 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.

História
ReleaseMudanças
19 R6Classe adicionada

Exemplo

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é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ória
ReleaseMudanças
20Validação TLS por padrão
18 R6Support of automaticRedirections and decodeData properties

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

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

Descrição

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. A sintaxe a utilizar é:

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

options parameter

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

PropriedadeTipoDescriçãoPor padrão
automaticRedirectionsParâmetrosSe true, os redirecionamentos serão realizados automaticamente (até 5 redirecionamentos são tratados, a resposta do 6. º redirecionamento é retornada, se houver)True
bodyDiferente deBody of the request (required in case of post or 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
certificatesFolderFolderDefine a pasta de certificados de cliente activosindefinido
dataTypeTextTipo de atributo do corpo de resposta. Valores: "texto", "blob", "objecto", ou "auto". Se "auto", o tipo do conteúdo do corpo será deduzido do seu tipo MIME (objecto para JSON, texto para texto, javascript, xml, mensagem http e forma codificada url, ou então um blob)"auto"
decodeDataParâmetrosIf true, the data received in the onData callback is uncompressedFalse
encodingTextUsed only in case of requests with a body (post or put methods). Codificação do conteúdo do corpo do pedido se for um texto, ignorado se o tipo de conteúdo for colocado dentro dos cabeçalhos"UTF-8"
headersObjectCabeçalhos do pedido. Syntax: headers.key=value (value can be a Collection if the same key must appear multiple times)Objecto vazio
methodText"POST", "GET", ou outro método"GET"
minTLSVersionTextSets the minimum version of TLS: "TLSv1_0", "TLSv1_1", "TLSv1_2", "TLSv1_3""TLSv1_2"
onDataFunctionChamada de retorno quando os dados do corpo são recebidos. Recebe dois objectos como parâmetros (ver abaixo)indefinido
onErrorFunctionChamada de retorno quando ocorre um erro. Recebe dois objectos como parâmetros (ver abaixo)indefinido
onHeadersFunctionChamada de retorno quando os cabeçalhos são recebidos. Recebe dois objectos como parâmetros (ver abaixo)indefinido
onResponseFunctionChamada de retorno quando uma resposta é recebida. Recebe dois objectos como parâmetros (ver abaixo)indefinido
onTerminateFunctionChamada de retorno quando o pedido estiver terminado. Recebe dois objectos como parâmetros (ver abaixo)indefinido
protocolText"auto" ou "HTTP1". "auto" significa HTTP1 na implementação actual"auto"
proxyAuthenticationauthentication objectAutenticação por procuração de tratamento de objectosindefinido
serverAuthenticationauthentication objectAutenticação do servidor de tratamento de objectosindefinido
returnResponseBodyParâmetrosIf 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. Indefinido = sem timeoutIndefinido
validateTLSCertificateParâmetrosSe false, 4D não valida o certificado TLS e não retorna um erro se ele for inválido (i.e. expirado, auto-assinado...). Importante: Na implementação actual, a Autoridade de Certificação em si não é verificada.True

Funções Callback

Todas as funções de chamada de retorno recebem dois parâmetros de objectos:

ParâmetroTipo
$param1HTTPRequest object
$param2Event object

Aqui está a sequência de chamadas 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

objecto evento

An event object is returned when a callback function is called. Contém as seguintes propriedades:

PropriedadeTipoDescrição
.datablobDados recebidos. It is always undefined except in the onData callback
.typetextTipo de evento. Possíveis valores: "resposta", "erro", "cabeçalhos", "dados", ou "terminar

authentication-object

An authentication object handles the options.serverAuthentication or options.proxyAuthentication property. Pode conter as seguintes propriedades:

PropriedadeTipoDescriçãoPor padrão
nameTextNome utilizado para autenticaçãoindefinido
senhaTextSenha utilizada para autenticaçãoindefinido
methodTextMétodo utilizado para autenticação: "basic", "digest", "auto"."auto"

HTTP Parse message

História
ReleaseMudanças
20 R4Adicionado

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

ParâmetroTipoDescrição
dataText, Blob->Dados a serem analisados
ResultadosObject<-Objeto, cada propriedade é uma parte dos dados de várias partes

Descrição

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 em si, é um protocolo de comunicação sem estado. Neste quadro, os clientes iniciam uma comunicação enviando mensagens "request" aos servidores, especificando detalhes como método, alvo, cabeçalhos, conteúdo, etc. Os servidores, respondem com mensagens de "resposta" que incluem os mesmos detalhes. HTTP Parse message parses either the "request" or the "response" message into a well-organized object.

Exemplo

No exemplo a seguir, analisamos os dados de um arquivo de texto que contém solicitações HTTP.

Aqui está o conteúdo do arquivo:

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 analisar o arquivo:

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

Descrição

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

.encoding

encoding : Text

Descrição

The .encoding property contains 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
errorsCollectionpilha de erros 4D em caso de erro
[].errCodeNumberCódigo de erro 4D
[].messageTextDescrição do erro 4D
[].componentSignatureTextAssinatura da componente interna que devolveu o erro

.headers

headers : Object

Descrição

The .headers property contains the headers passed in the options object when calling new(). Se foi omitido, contém um objecto vazio.

.method

method : Text

Descrição

The .method property contains the method passed in the options object when calling new(). Se foi omitido, contém "GET".

.protocol

protocol : Text

Descrição

The .protocol property contains the protocol passed in the options object when calling new(). Se foi omitido ou se "auto" foi utilizado, contém a versão do protocolo utilizado.

.response

História
ReleaseMudanças
19 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. Contém as seguintes propriedades:

PropriedadeTipoDescrição
.bodyDiferente deCorpo da resposta. The type of the message is defined according to the dataType property. Indefinido se o corpo ainda não tiver sido recebido
.headersObjectCabeçalhos da resposta. Os nomes dos cabeçalhos são devolvidos em minúsculas. <headername>.key = value (value can be a collection if the same key appears multiple times). Indefinido se os cabeçalhos ainda não tiverem sido recebidos.
.statusNumberCódigo de estado da resposta
.statusTextTextMensagem que explica o código de estado
.rawHeadersObjectCabeçalhos da resposta. Os nomes dos cabeçalhos são devolvidos intactos (com o seu caso original). <headerName>.key = value (value can be a collection if the same key appears multiple times). Indefinido se os cabeçalhos ainda não tiverem sido recebidos.

.returnResponseBody

returnResponseBody : Boolean

Descrição

The .returnResponseBody property contains the returnResponseBody passed in the options object when calling new(). Se foi omitido, contém True.

.terminate()

.terminate()

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

Descrição

Esta função é thread segura.

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

.terminated

terminated : Boolean

Descrição

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

.timeout

timeout : Real

Descrição

The .timeout property contains the timeout passed in the options object when calling new(). Se foi omitido, contém Indefinido.

.url

url : Text

Descrição

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

.wait()

.wait( { time : Real } ) : HTTPRequestClass

ParâmetroTipoDescrição
timeReal->Tempo máximo em segundos para esperar pela resposta
Resultados4D.HTTPRequest<-HTTPRequest object

Descrição

Esta função é thread segura.

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.

Se a resposta do servidor já tiver chegado, a função regressa imediatamente.