Http

Moduleejs
Definition class Http
InheritanceHttp inherit Object
Specifiedejscript-2.5
StabilityEvolving (.

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

QualifiersPropertyTypeDescription
static const AcceptedNumberHTTP Accepted Status (202).
static const BadGatewayNumberHTTP Bad Gateway Status (502) 0.
static const BadRequestNumberHTTP Bad Request Status(400).
static const ContinueNumberHTTP Continue Status (100).
static const CreatedNumberHTTP Created Status (201).
static const GatewayTimeoutNumberHTTP Gateway Timeout Status (504).
static const MovedPermanentlyNumberHTTP Moved Permanently Status (301).
static const MovedTemporarilyNumberHTTP Found but Moved Temporily Status (302).
static const MultipleChoiceNumberHTTP Multiple Choices Status (300).
static const NoContentNumberHTTP No Content Status (204) 0.
static const NotAuthoritativeNumberHTTP Non-Authoritative Information Status (203).
static const NotModifiedNumberHTTP Not Modified Status (304).
static const OkNumberHTTP Success Status (200).
static const PartialContentNumberHTTP Partial Content Status (206).
static const ResetNumberHTTP Reset Content Status (205).
static const SeeOtherNumberHTTP See Other Status (303).
static const BadMethodNumberHTTP Method Not Allowed Status (405).
static const ConflictNumberHTTP Conflict Status (409).
static const ForbiddenNumberHTTP Forbidden Status (403).
static const NotAcceptableNumberHTTP Not Acceptable Status (406).
static const NotFoundNumberHTTP Not Found Status (404).
static const EntityTooLargeNumberHTTP Request Entity Too Large Status (413).
static const GoneNumberHTTP Gone Status (410).
static const LengthRequiredNumberHTTP Length Required Status (411).
static const PaymentRequiredNumberHTTP Payment Required Status (402).
static const PrecondFailedNumberHTTP Precondition Failed Status (412) 8.
static const ProxyAuthRequiredNumberHTTP ProxyAuthentication Required Status (407).
static const RequestTimeoutNumberHTTP Request Timeout Status (408).
static const ServiceUnavailableNumberHTTP Service Unavailable Status (503) 8.
static const UnauthorizedNumberHTTP Unauthorized Status (401).
static const BadRangeNumberHTTP Requested Range Not Satisfiable (416).
static const NotImplementedNumberHTTP Not Implemented Status (501).
static const ServerErrorNumberHTTP Server Error Status (500).
static const UnsupportedMediaNumberHTTP Unsupported Media Type (415).
static const UriTooLongNumberHTTP Request URI Too Long Status (414).
static const UseProxyNumberHTTP Use Proxy Status (305).
static const VersionNotSupportedNumberHTTP Http Version Not Supported Status (505).
get set asyncBooleanThe current async mode. Set to true if the stream is in async mode.
get set caPathFilename of the certificate bundle used to verify server certificates. This file contains catenated CA certificates in PEM format. (.
get set certificatePathFilename of the certificate used to identify the client. This file contains the client certificate in PEM format.
get contentLengthNumberResponse 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 contentTypeStringResponse content type derrived from the response Http Content-Type header. To set the request body Content-Type, use setHeader("Content-Type", MimeType).
get dateDateWhen the response was generated. Response date derrived from the response Http Date header.
get finalizedBooleanHas the request output been finalized.
get set followRedirectsBooleanControl 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 headersObjectResponse 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 isSecureBooleanIs the connection is utilizing SSL.
get set keyPathFilename of the private key to use with the certificate for SSL communications. This file contains the client certificate in PEM format.
get lastModifiedDateWhen 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 limitsObjectResource limits for requests.
get set methodStringHttp request method for this Http object. Default is "GET". Typical methods are: GET, POST, HEAD, OPTIONS, PUT, DELETE and TRACE. 0.
get set responseStringResponse 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 sessionCookieStringGet 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 statusNumberHttp 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 statusMessageStringDescriptive 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 uriUriThe current Uri for this Http object. The Uri is used for the request URL when making a connect call. (.
get set verifyBooleanVerify peer certificates. Setting verify to true will also set verifyIssuer to the same value.
get set verifyIssuerBooleanVerify 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

QualifiersMethod
static fetch(uri: Uri, method: String = GET, data: Array): String
 Convenience routine to fetch a URI and return the response.

Http Instance Methods

QualifiersMethod
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)
Description
Create an Http object. The object is initialized with the Uri.
Parameters
uri: Uri The (optional) Uri to initialize with. [default: null]
Throws
IOError: if the Uri is malformed.

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
closeA close event is issued before closing the stream.

connect(method: String, uri: Uri = null, data: Array): Http
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

static fetch(uri: Uri, method: String = GET, data: Array): String
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.

flush(dir: Number = expression): Void
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.
Parameters
dir: Number Direction to flush. Set to READ WRITE or BOTH. [default: expression]

form(uri: Uri, data: Object): Http
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.

get(uri: Uri = null, data: Array): Http
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.

head(uri: Uri = null): Http
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.

header(key: String): String
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.

off(name, observer: Function): Void
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.

on(name, observer: Function): Http
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
readableIssued when the stream becomes readable.
writableIssued when the stream becomes writable.
closeIssued when stream is being closed. 8.
headersIssued when the response headers have been fully received.
readableIssued when some body content is available.
writableIssued when the connection is writable to accept body data (PUT, POST).
completeIssued when the request completes. Complete is always issued whether the request errors or not.
errorIssued if the request does not complete successfully. This is not issued if the request ompletes successfully but with a non 200 Http status code.

post(uri: Uri, data: Array): Http
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.

put(uri: Uri, data: Array): Http
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.

read(buffer: ByteArray, offset: Number = 0, count: Number = -1): Number
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
readableIssued when there is new read data available.
writableIssued when the stream becomes empty. `.
Returns
A count of the bytes actually read. Returns null on EOF or errors.

readLines(count: Number = -1): Array
Description
Read the request response as an array of lines. This call will block and should not be used in async mode.
Parameters
count: Number Of linese to read. Returns the entire response contents if count is -1. [default: -1]
Returns
An array of strings.
Throws
IOError: if an I/O error occurs.

readString(count: Number = -1): String
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.

setCookie(cookie: String): Void
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.

setCredentials(username: String, password: String, type: String = null): Void
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]

setHeader(key: String, value: String, overwrite: Boolean = true): Void
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]

setHeaders(headers: Object, overwrite: Boolean = true): Void
Description
Set request headers. Use setHeader() to set a single header. Use getRequestHeaders() to retrieve and examine the request headers set.
Parameters
headers: Object Object hash of headers to set.
overwrite: Boolean If true, the new set of headers completely replaces the existing set of request headers. If overwrite is false, a new header value will be catenated to the old value after a ", " separator. [default: true]

setLimits(limits: Object): Void
Description
Update the request resource limits. The supplied limit fields are updated. See limit for limit field details.
Parameters
limits: Object Object hash of limit fields and values.
See Also
limits

trace(options: Object): Void
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 }
})

upload(uri: String, files: Object, fields: Object = null): Http
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)

wait(timeout: Number = -1): Boolean
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.

write(data: Array): Number
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
readableIssued when data is written and a consumer can read without blocking.
writableIssued 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.