Http
Module | ejs |
Definition | class Http |
Inheritance | Http ![]() |
Specified | ejscript-2.5 |
Stability | Evolving (. |
The Http object represents a Hypertext Transfer Protocol version 1.1 client connection.
It is used to issue HTTP requests and capture responses. It supports the HTTP/1.1 standard including methods for GET, POST, PUT, DELETE, OPTIONS, and TRACE. It also supports Keep-Alive and SSL connections.
Properties
Qualifiers | Property | Type | Description |
---|---|---|---|
static const | Accepted | Number | HTTP Accepted Status (202). |
static const | BadGateway | Number | HTTP Bad Gateway Status (502) 0. |
static const | BadRequest | Number | HTTP Bad Request Status(400). |
static const | Continue | Number | HTTP Continue Status (100). |
static const | Created | Number | HTTP Created Status (201). |
static const | GatewayTimeout | Number | HTTP Gateway Timeout Status (504). |
static const | MovedPermanently | Number | HTTP Moved Permanently Status (301). |
static const | MovedTemporarily | Number | HTTP Found but Moved Temporily Status (302). |
static const | MultipleChoice | Number | HTTP Multiple Choices Status (300). |
static const | NoContent | Number | HTTP No Content Status (204) 0. |
static const | NotAuthoritative | Number | HTTP Non-Authoritative Information Status (203). |
static const | NotModified | Number | HTTP Not Modified Status (304). |
static const | Ok | Number | HTTP Success Status (200). |
static const | PartialContent | Number | HTTP Partial Content Status (206). |
static const | Reset | Number | HTTP Reset Content Status (205). |
static const | SeeOther | Number | HTTP See Other Status (303). |
static const | BadMethod | Number | HTTP Method Not Allowed Status (405). |
static const | Conflict | Number | HTTP Conflict Status (409). |
static const | Forbidden | Number | HTTP Forbidden Status (403). |
static const | NotAcceptable | Number | HTTP Not Acceptable Status (406). |
static const | NotFound | Number | HTTP Not Found Status (404). |
static const | EntityTooLarge | Number | HTTP Request Entity Too Large Status (413). |
static const | Gone | Number | HTTP Gone Status (410). |
static const | LengthRequired | Number | HTTP Length Required Status (411). |
static const | PaymentRequired | Number | HTTP Payment Required Status (402). |
static const | PrecondFailed | Number | HTTP Precondition Failed Status (412) 8. |
static const | ProxyAuthRequired | Number | HTTP ProxyAuthentication Required Status (407). |
static const | RequestTimeout | Number | HTTP Request Timeout Status (408). |
static const | ServiceUnavailable | Number | HTTP Service Unavailable Status (503) 8. |
static const | Unauthorized | Number | HTTP Unauthorized Status (401). |
static const | BadRange | Number | HTTP Requested Range Not Satisfiable (416). |
static const | NotImplemented | Number | HTTP Not Implemented Status (501). |
static const | ServerError | Number | HTTP Server Error Status (500). |
static const | UnsupportedMedia | Number | HTTP Unsupported Media Type (415). |
static const | UriTooLong | Number | HTTP Request URI Too Long Status (414). |
static const | UseProxy | Number | HTTP Use Proxy Status (305). |
static const | VersionNotSupported | Number | HTTP Http Version Not Supported Status (505). |
get set | async | Boolean | The current async mode. Set to true if the stream is in async mode. |
get set | ca | Path | Filename of the certificate bundle used to verify server certificates. This file contains catenated CA certificates in PEM format. (. |
get set | certificate | Path | Filename of the certificate used to identify the client. This file contains the client certificate in PEM format. |
get | contentLength | Number | Response content body length. Set to the length of the response body in bytes or -1 if no body or not known. To set the request body Content-Length, use setHeader("Content-Length", Length). |
get | contentType | String | Response content type derrived from the response Http Content-Type header. To set the request body Content-Type, use setHeader("Content-Type", MimeType). |
get | date | Date | When the response was generated. Response date derrived from the response Http Date header. |
get | finalized | Boolean | Has the request output been finalized. |
get set | followRedirects | Boolean | Control whether redirects should be automatically followed by this Http object. When true, a redirected response will be followed and the redirected URL will be transparently re-fetched. Default is false. |
get | headers | Object | Response headers. Use header() to retrieve a single header value. Set to an object filled with all the response headers. If multiple headers of the same key value are defined, their contents will be catenated with a ", " separator as per the HTTP/1.1 specification. 0. |
get | isSecure | Boolean | Is the connection is utilizing SSL. |
get set | key | Path | Filename of the private key to use with the certificate for SSL communications. This file contains the client certificate in PEM format. |
get | lastModified | Date | When the response content was last modified. Set to the the value of the response Http Last-Modified header. Set to null if not known. |
get | limits | Object | Resource limits for requests. |
get set | method | String | Http request method for this Http object. Default is "GET". Typical methods are: GET, POST, HEAD, OPTIONS, PUT, DELETE and TRACE. 0. |
get set | response | String | Response body content as a string. The first time this property is read, the response content will be read and buffered. Don't use this property in async mode as it will block. Set to the response as a string of characters. If the response has no body content, the empty string will be returned. |
get | sessionCookie | String | Get the ejs session cookie. This call extracts the ejs session cookie from the Http response headers. Ejscript sessions are identified by a client cookie which when transmitted with subsequent requests will permit the server to locate the relevant session state store for the server-side application. Use: setCookie(cookie) to transmit the cookie on subsquent requests. Will be a string or null if there is no session cookie defined. |
get | status | Number | Http response status code from the Http response status line, e.g. 200. Set to null if unknown. This command will block until the request completes. |
get | statusMessage | String | Descriptive status message for the Http response. This message may come from either the HTTP response status line or from a local error message if the response fails to parse. |
get set | uri | Uri | The current Uri for this Http object. The Uri is used for the request URL when making a connect call. (. |
get set | verify | Boolean | Verify peer certificates. Setting verify to true will also set verifyIssuer to the same value. |
get set | verifyIssuer | Boolean | Verify the certificate issuer. If false, then the the certificate verification process will accept certificates for which the issuer cannot be verified. This permits self-signed certificates to be accepted. |
Http Class Methods
Qualifiers | Method |
---|---|
static | fetch(uri: Uri, method: String = GET, data: Array): String |
Convenience routine to fetch a URI and return the response. |
Http Instance Methods
Qualifiers | Method |
---|---|
Http(uri: Uri = null) | |
Create an Http object. | |
close(): Void | |
Close the stream.This immediately closes any open network connection and resets the http object to be ready for another connection. | |
connect(method: String, uri: Uri = null, data: Array): Http | |
Commence a HTTP request for the current method and uri. | |
finalize(): Void | |
Signals the end of any write data and flushes any buffered write data to the server. | |
flush(dir: Number = expression): Void | |
Flush the stream and underlying streams.Flush request data. | |
form(uri: Uri, data: Object): Http | |
Commence a POST request with www-url encoded key=value data. | |
get(uri: Uri = null, data: Array): Http | |
Commence a GET request for the current uri. | |
getRequestHeaders(): Object | |
Get the (proposed) request headers that will be sent with the request. | |
head(uri: Uri = null): Http | |
Commence a HEAD request for the current uri. | |
header(key: String): String | |
Get the value of a single response header. | |
off(name, observer: Function): Void | |
Remove an observer from the stream. | |
on(name, observer: Function): Http | |
Add an observer to the stream for the named events.All events are called with the following signature. | |
post(uri: Uri, data: Array): Http | |
Initiate a POST request. | |
put(uri: Uri, data: Array): Http | |
Commence a PUT request for the current uri. | |
read(buffer: ByteArray, offset: Number = 0, count: Number = -1): Number | |
Read a data from the stream.h. | |
readLines(count: Number = -1): Array | |
Read the request response as an array of lines. | |
readString(count: Number = -1): String | |
Read the response as a string. | |
readXml(): XML | |
Read the request response as an XML document. | |
reset(): Void | |
Reset the Http object to prepare for a new request. | |
setCookie(cookie: String): Void | |
Set a "Cookie" header in the request headers. | |
setCredentials(username: String, password: String, type: String = null): Void | |
Set the user credentials to use if the request requires authentication. | |
setHeader(key: String, value: String, overwrite: Boolean = true): Void | |
Set a request header. | |
setHeaders(headers: Object, overwrite: Boolean = true): Void | |
Set request headers. | |
setLimits(limits: Object): Void | |
Update the request resource limits. | |
trace(options: Object): Void | |
Configure request tracing for the request. | |
upload(uri: String, files: Object, fields: Object = null): Http | |
Upload files using multipart/mime. | |
wait(timeout: Number = -1): Boolean | |
Wait for a request to complete. | |
write(data: Array): Number | |
Write data to the stream.Write body data to the server. |
Method Detail
Http(uri: Uri = null)
close(): Void
- Description
- Close the stream.This immediately closes any open network connection and resets the http object to be ready for another connection. Connections should be explicitly closed rather than relying on the garbage collector to dispose of the Http object and automatically close the connection. If you have more requests that can be issued on the same network connection, use reset() rather than close to prepare for a new request on the same connection.
- Events
close A close event is issued before closing the stream.
- Description
- Commence a HTTP request for the current method and uri. The HTTP method should be defined via the method property and Uri via the uri property. This routine is typically not used. Rather it is invoked via one of the Http methods get() head() post() instead. This call, and the Http method calls may not immediately initiate the connection. The Http class will delay connections until finalize() is called explicitly or implicitly reading status or response content. This enables the request content length to be determined automatically for smaller requests where the request body data can be buffered and measured before sending the request headers.
- Parameters
method: String Http method. This is typically "GET" or "POST". uri: Uri New uri to use. This overrides any previously defined uri for the Http object. [default: null] data: Array Data objects to send with the request. Data is written raw and is not encoded or converted. However, the routine intelligently handles arrays such that, each element of the array will be written.
- Throws
- IOError: if the request cannot be issued to the remote server. Once the connection has been made, exceptions will not be thrown and $status must be consulted for request status. X
- Description
- Convenience routine to fetch a URI and return the response. This routine is a simple, one-liner to fetch a remote resource using Http. This routine is deliberatly inconsistent with connect(), in that is accepts the URI to fetch as the first parameter and assumes a default method of GET.
- Parameters
uri: Uri New uri to use. This overrides any previously defined uri for the Http object. method: String Http method. Defaults to GET. [default: GET] data: Array Data objects to send with the request. Data is written raw and is not encoded or converted. However, the routine intelligently handles arrays such that, each element of the array will be written.
- Throws
- IOError: if the Uri is malformed
finalize(): Void
- Description
- Signals the end of any write data and flushes any buffered write data to the server.
- Description
- Flush the stream and underlying streams.Flush request data. A supplied flush direction argument modifies the effect of this call. If direction is set to Stream.READ, then all read data is discarded. If direction is set to Stream.WRITE, any buffered data is written. Stream.BOTH will cause both directions to be flushed. If the stream is in sync mode, this call will block until all data is written. If the stream is in async mode, it will attempt to write all data but will return immediately. Defaults to Stream.WRITE.Flush will force buffered request data to be sent immediately to the server.
- Description
- Commence a POST request with www-url encoded key=value data. See connect() for connection details. This will encode each data objects as a string of "key=value" pairs separated by "&" characters. After writing data, form() will call finalize().
- Parameters
uri: Uri Optional request uri. If non-null, this overrides any previously defined uri for the Http object. If null, use a previously defined uri. data: Object Optional object hash of key value pairs to use as the post data. These are www-url-encoded and the content mime type is set to "application/x-www-form-urlencoded".
- Throws
- IOError: if the request cannot be issued to the remote server.
- Description
- Commence a GET request for the current uri. See connect() for connection details. This call initiates a GET request. It does not wait for the request to complete. The get() method will call finalize. If you need to send body content with a get request, use connect(). Once initiated, one of the read or response routines may be used to receive the response data.
- Parameters
uri: Uri The uri to get. This overrides any previously defined uri for the Http object. If null, use a previously defined uri. [default: null] data: Array Data objects to send with the request. Data is written raw and is not encoded or converted. However, the routine intelligently handles arrays such that, each element of the array will be written.
- Throws
- IOError: if the request cannot be issued to the remote server. Once the connection has been made, exceptions will not be thrown and $status must be consulted for request status.
getRequestHeaders(): Object
- Description
- Get the (proposed) request headers that will be sent with the request. Use headers to get the response headers or header(key) to get a single response header.
- Returns
- The set of request headers that will be used when the request is sent. 8.
- Description
- Commence a HEAD request for the current uri. See connect() for connection details.
- Parameters
uri: Uri The request uri. This overrides any previously defined uri for the Http object. If null, use a previously defined uri. [default: null]
- Throws
- IOError: if the request cannot be issued to the remote server.
- Description
- Get the value of a single response header. This is a higher performance API than using response.headers["key"].
- Parameters
key: String Header key value to lookup. The lookup is caseless, i.e. the key can be any case of mix of case.
- Returns
- The header field value as a string or null if not known.
- Description
- Remove an observer from the stream.
- Parameters
name Event name previously used with observe. The name may be an array of events. observer: Function Observer function previously used with observe.
- Description
- Add an observer to the stream for the named events.All events are called with the following signature. The "this" object will be set to the instance object if the callback is a method. Otherwise, "this" will be set to the Http instance. If Function.bind may also be used to define the "this" object and to inject additional callback arguments. function (event: String, http: Http): Void.
- Parameters
name: [String|Array] Name of the event to listen for. The name may be an array of events. observer: Function Callback observer function. The function is called with the following signature: function observer(event: String, ...args): Void.
- Events
readable Issued when the stream becomes readable. writable Issued when the stream becomes writable. close Issued when stream is being closed. 8. headers Issued when the response headers have been fully received. readable Issued when some body content is available. writable Issued when the connection is writable to accept body data (PUT, POST). complete Issued when the request completes. Complete is always issued whether the request errors or not. error Issued if the request does not complete successfully. This is not issued if the request ompletes successfully but with a non 200 Http status code.
- Description
- Initiate a POST request. This call initiates a POST request. It does not wait for the request to complete. Posted data is NOT URL encoded. If you want to post data to a form, consider using the form method instead which automatically URL encodes the data. After writing data, post() will call finalize(). Post data may be supplied may alternatively via write.
- Parameters
uri: Uri Optional request uri. If non-null, this overrides any previously defined uri for the Http object. If null, use a previously defined uri. data: Array Data objects to send with the post request. Data is written raw and is not encoded or converted.
- Throws
- IOError: if the request cannot be issued to the remote server.
- Description
- Commence a PUT request for the current uri. See connect() for connection details. If a contentLength has not been previously defined for this request, chunked transfer encoding will be enabled.
- Parameters
uri: Uri The uri to put. This overrides any previously defined uri for the Http object. If null, use a previously defined uri. data: Array Optional data objects to write to the request stream. Data is written raw and is not encoded or converted. However, put intelligently handles arrays such that, each element of the array will be written. If encoding of put data is required, use the BinaryStream filter. If no putData is supplied, and the ContentLength header is non-zero you must call write to supply the body data. data: Array Optional object hash of key value pairs to use as the post data.
- Throws
- IOError: if the request cannot be issued to the remote server.
- Description
- Read a data from the stream.h. If data is available, the call will return immediately. If no data is available and the stream is in sync mode, the call will block until data is available. If no data is available and the stream is in async mode, the call will not block and will return immediately. In this case a "readable" event will be issued when data is available for reading.
- Parameters
buffer: ByteArray Destination byte array for read data. offset: Number Offset in the byte array to place the data. If the offset is -1, then data is appended to the buffer write position which is then updated. If offset is >= 0, the data is read to the offset and the read pointer is set to the offset and the write pointer to one past the end of the data just read. [default: 0] count: Number Read up to this number of bytes. If -1, read as much as the buffer will hold up. If the stream is of fixed and known length (such as a file) and the buffer is of sufficient size or is growable, read the entire stream. If the buffer is of a fixed size, ready only what will fit into the buffer. [default: -1]
- Events
readable Issued when there is new read data available. writable Issued when the stream becomes empty. `.
- Returns
- A count of the bytes actually read. Returns null on EOF or errors.
- Description
- Read the response as a string. This call will block and should not be used in async mode.
- Parameters
count: Number Of bytes to read. Returns the entire response contents if count is -1. [default: -1]
- Returns
- A string of count characters beginning at the start of the response data.
- Throws
- IOError: if an I/O error occurs.
readXml(): XML
- Description
- Read the request response as an XML document. This call will block and should not be used in async mode.
- Returns
- The response content as an XML object.
- Throws
- IOError: if an I/O error occurs.
reset(): Void
- Description
- Reset the Http object to prepare for a new request. This will discard existing headers and security credentials. It will not close the connection to TCP/IP and thus Keep-Alive will be maintained.
- Description
- Set a "Cookie" header in the request headers. This is used to send a cookie to the server.
- Parameters
cookie: String Cookie header value.
- Description
- Set the user credentials to use if the request requires authentication.
- Parameters
username: String String user name to use. If null, then reset the current credentials. The password may be included in the username by appending a ":" then the password. In this case set the password parameter to null. password: String Un-encrypted string password to use. Set to null to reset the current credentials. type: String Authentication type. Set to basic or digest. Defaults to basic. If not set, then the authentication type is determined by the response from the server and the request will be retried if it fails with an authentication error. h. [default: null]
- Description
- Set a request header. Use setHeaders() to set all the headers. Use getRequestHeaders() to retrieve and examine the request header set.
- Parameters
key: String The header keyword for the request, e.g. "accept". value: String The value to associate with the header, e.g. "yes". overwrite: Boolean If the header is already defined and overwrite is true, then the new value will overwrite the old. If overwrite is false, the new value will be catenated to the old value with a ", " separator. [default: true]
- Description
- Set request headers. Use setHeader() to set a single header. Use getRequestHeaders() to retrieve and examine the request headers set.
- Description
- Configure request tracing for the request. The default is to trace the first line of requests and responses at level 2 and to trace headers at level 3. The options argument contains optional properties. These may contain an object hash which describes the following fields:.
- Parameters
options: Object Set of trace options with properties for: The connection property specifies that new connections should be traced. The error property specifies that new connections should be traced. The info property specifies that new connections should be traced. The rxFirst property specifies that the first line of the request should be traced. The rxHeaders property specifies that the headers (including first line) of the request should be traced. The rxBody property specifies that the body content of the request should be traced. The txFirst property specifies that the first line of the response should be traced. The txHeaders property specifies that the headers (including first line) of the response should be traced. The txBody property specifies that the body content of the request should be traced. The complete property specifies that the body content of the request should be traced. The size property specifies a maximum body size in bytes that will be traced. Content beyond this limit will not be traced.
- Example
trace({ "rxHeaders": 3, "rxBody": 4, size: 1000000 } })
- Description
- Upload files using multipart/mime. This routine initiates a POST request and sends the specified files and form fields using multipart mime encoding. This call is synchronous (blocks) until complete.
- Parameters
uri: String The uri to upload to. This overrides any previously defined uri for the Http object. files: Object Object hash of files to upload. fields: Object Object hash of of form fields to send. [default: null]
- Example
fields = { name: "John Smith", address: "700 Park Avenue" } files = { file1: "a.txt, file2: "b.txt" } http.upload(URL, files, fields)
- Description
- Wait for a request to complete. This will call finalize() if in sync mode and the request is not already finalized.
- Parameters
timeout: Number Timeout in milliseconds to wait for the request to complete. A timeout of zero means don't block. A timeout of < 0 (default), means use the default request timeout. [default: -1]
- Returns
- True if the request successfully completes.
- Description
- Write data to the stream.Write body data to the server. If the stream can accept all the write data, the call returns immediately with the number of bytes written. If writing more data than the stream can absorb in sync mode, the call will block until the data is written. If writing more data than the stream can absorb in async mode, the call will not block and will buffer the data and return immediately. Some streams will require a flush() call to actually send the data. A "writable" event will be issued when the stream can again absorb more data.This will buffer the written data until either flush() or finalize() is called. The Http "Content-Length" header should normally be set prior to writing any data for optimial data transfter. If the Content-Length header has not been defined, the data will be transferred using chunked transfers. 0
- Parameters
data: Array Data to write.
- Events
readable Issued when data is written and a consumer can read without blocking. writable Issued when the stream becomes empty and it is ready to be written to.
- Returns
- A count of the bytes actually written.
- Throws
- IOError: if there is an I/O error.