Http

Moduleejs.io
Definition class Http
InheritanceHttp inherit Object
Specifiedejscript-1.1
StabilityPrototype.

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
public static const AcceptedNumberHTTP Accepted Status (202).
public static const BadGatewayNumberHTTP Bad Gateway Status (502).
public static const BadMethodNumberHTTP Method Not Allowed Status (405).
public static const BadRangeNumberHTTP Requested Range Not Satisfiable (416).
public static const BadRequestNumberHTTP Bad Request Status(400).
public static const ConflictNumberHTTP Conflict Status (409).
public static const ContinueNumberHTTP Continue Status (100).
public static const CreatedNumberHTTP Created Status (201).
public static const EntityTooLargeNumberHTTP Request Entity Too Large Status (413).
public static const ForbiddenNumberHTTP Forbidden Status (403).
public static const GatewayTimeoutNumberHTTP Gateway Timeout Status (504).
public static const GoneNumberHTTP Gone Status (410).
public static const LengthRequiredNumberHTTP Length Required Status (411).
public static const MovedPermanentlyNumberHTTP Moved Permanently Status (301).
public static const MovedTemporarilyNumberHTTP Found but Moved Temporily Status (302).
public static const MultipleChoiceNumberHTTP Multiple Choices Status (300).
public static const NoContentNumberHTTP No Content Status (204).
public static const NotAcceptableNumberHTTP Not Acceptable Status (406).
public static const NotAuthoritativeNumberHTTP Non-Authoritative Information Status (203).
public static const NotFoundNumberHTTP Not Found Status (404).
public static const NotImplementedNumberHTTP Not Implemented Status (501).
public static const NotModifiedNumberHTTP Not Modified Status (304).
public static const OkNumberHTTP Success Status (200).
public static const PartialContentNumberHTTP Partial Content Status (206).
public static const PaymentRequiredNumberHTTP Payment Required Status (402).
public static const PrecondFailedNumberHTTP Precondition Failed Status (412).
public static const ProxyAuthRequiredNumberHTTP ProxyAuthentication Required Status (407).
public static const ReadNumberCallback event mask for readable events.
public static const RequestTimeoutNumberHTTP Request Timeout Status (408).
public static const ResetNumberHTTP Reset Content Status (205).
public static const SeeOtherNumberHTTP See Other Status (303).
public static const ServerErrorNumberHTTP Server Error Status (500).
public static const ServiceUnavailableNumberHTTP Service Unavailable Status (503).
public static const UnauthorizedNumberHTTP Unauthorized Status (401).
public static const UnsupportedMediaNumberHTTP Unsupported Media Type (415).
public static const UriTooLongNumberHTTP Request URI Too Long Status (414).
public static const UseProxyNumberHTTP Use Proxy Status (305).
public static const VersionNotSupportedNumberHTTP Http Version Not Supported Status (505).
public static const WriteNumberCallback event mask for writeable events.
public get codeNumberHttp response status code. Set to an integer value or -1 if the Http response code is not known. e.g. 200.
public get codeStringStringHttp response message from the Http response status line, e.g. OK. This is the additional text added to the first line in the Http protocol response.
public get setcontentLengthNumberRequest/Response body length. Reading this property, will return the response content body length. The value will be the response body length in bytes or -1 if no body or if the body length is not known. Setting this value will set the outgoing request body length. This will set the request Content-Length header value and is used when using write to manually send the requeset body data. WARNING: This API will change in the next release. It will become a sole getter. Use addHeader to define a Content-Length header if you require defining a request body content length.
public get contentTypeStringResponse content type derrived from the response Http Content-Type header.
public get dateDateWhen the response was generated. Response date derrived from the response Http Date header.
public get expiresDateWhen the response content expires. This is derrived from the response Http Expires header.
public get setfollowRedirectsBooleanWill response redirects be automatically followed by this Http object. If true, the Http class will automatically reissue requests if redirected by the server.
public get headersArrayResponse headers. Use header() to retrieve a single header value.
public get isSecureBooleanIs the connection is utilizing SSL.
public 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.
public get setmethodStringHttp request method for this Http object.
public get responseStringResponse body content. The first time this property is read, the response content will be read and buffered. Set to the response as a string of characters. If the response has no body content, the empty string will be returned.
public get settimeoutNumberRequest timeout in milliseconds. This is the idle timeout value. If the request has no I/O activity for this time period, it will be retried or aborted.
public get seturiStringURI for this Http object.

Http Methods

QualifiersMethod
public addHeader(key: String, value: String, overwrite: Boolean = true): Void
 Add a request header.
public close(graceful: Boolean = true): Void
 Close the connection to the server and free up all associated resources.
public connect(uri: String = null, data: Array): Void
 Issue a HTTP request for the current method and uri.
public del(uri: String = null, data: Array): Void
 Issue a DELETE request for the current uri.
public flush(graceful: Boolean = true): Void
 Flush any buffered write data.
public form(uri: String, postData: Object): Void
 Issue a POST request with form data the current uri.
public get(uri: String = null, data: Array): Void
 Issue a GET request for the current uri.
public head(uri: String = null): Void
 Issue a HEAD request for the current uri.
public header(key: String): String
 Get the value of any response header field.
Http(uri: String = null)
 Create an Http object.
public static mimeType(path: String): String
 Get the mime type for a path or extension string.
public options(uri: String = null): Void
 Issue an OPTIONS request for the current uri.
public post(uri: String, data: Array): Void
 Initiate a POST request for the current uri.
public put(uri: String, data: Array): Void
 Issue a PUT request for the current uri.
public read(buffer: ByteArray, offset: Number = 0 , count: Number = -1): Number
 Read a block of response content data from the connection.
public readLines(count: Number = -1): Array
 Read the request response as an array of lines.
public readString(count: Number = -1): String
 Read the request response as a string.
public readXml(): XML
 Read the request response as an XML document.
public setCredentials(username: String, password: String): Void
 Set the user credentials to use if the request requires authentication.
public trace(uri: String = null): Void
 Issue a TRACE request for the current uri.
public upload(url: String, files: Object, fields: Object = null): Void
 Upload files using multipart/mime.
public wait(timeout: Number = -1): Boolean
 Wait for a request to complete.
public write(data: Array): Void
 Write body data to the request stream.

Method Detail

public addHeader(key: String, value: String, overwrite: Boolean = true): Void

Add a request header.

Description
Must be done before the Http request is issued.
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 true, overwrite existing headers of the same key name. [default: true]

public close(graceful: Boolean = true): Void

Close the connection to the server and free up all associated resources.

Description
This 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.
Parameters
graceful: Boolean If true, then close the socket gracefully after writing all pending data. [default: true]
Stability
Prototype.

public connect(uri: String = null, data: Array): Void

Issue a HTTP request for the current method and uri.

Description
The HTTP method should be defined via the method property and uri via the uri property. This routine is typically not used. Rather get, head, post or put are used instead.
Parameters
uri: String 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.

public del(uri: String = null, data: Array): Void

Issue a DELETE request for the current uri.

Description
This function will block until the the request completes or fails, unless a callback function has been defined. If a callback has been specified, this function will initiate the request and return immediately.
Parameters
uri: String The uri to delete. 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.

public flush(graceful: Boolean = true): Void

Flush any buffered write data.

Parameters
graceful: Boolean If true, then write all pending. [default: true]

public form(uri: String, postData: Object): Void

Issue a POST request with form data the current uri.

Description
This function will block until the the request completes or fails, unless a callback function has been defined. If a callback has been specified, this function will initiate the request and return immediately.
Parameters
uri: String Optional request uri. If non-null, this overrides any previously defined uri for the Http object.
postData: 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.

public get(uri: String = null, data: Array): Void

Issue a GET request for the current uri.

Description
This call initiates a GET request. It does not wait for the request to complete. Once initiated, one of the read or response routines may be used to receive the response data.
Parameters
uri: String The uri to get. 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.

public head(uri: String = null): Void

Issue a HEAD request for the current uri.

Description
This call initiates a HEAD request. Once initiated, read and write may be issued to send and receive data.
Parameters
uri: String The request uri. This overrides any previously defined uri for the Http object. [default: null]
Throws
IOError: if the request cannot be issued to the remote server.

public header(key: String): String

Get the value of any response header field.

Returns
The header field value as a string or null if not known.

public Http(uri: String = null)

Create an Http object.

Description
The object is initialized with the URI.
Parameters
uri: String The (optional) URI to initialize with. [default: null]
Throws
IOError: if the URI is malformed.

static public mimeType(path: String): String

Get the mime type for a path or extension string.

Description
NOTE: this routine will migrate to the Url class in the future.
Parameters
path: String Path or extension string to examine.
Returns
The mime type string.

public options(uri: String = null): Void

Issue an OPTIONS request for the current uri.

Description
Use readString to retrieve the response.
Parameters
uri: String New uri to use. This overrides any previously defined uri for the Http object. [default: null]
Throws
IOError: if the request cannot be issued to the remote server.

public post(uri: String, data: Array): Void

Initiate a POST request for the current uri.

Description
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. Post data may be supplied may alternatively be supplied via write.
Parameters
uri: String Optional request uri. If non-null, this overrides any previously defined uri for the Http object.
data: Array Data objects to send with the post request. Data is written raw and is not encoded or converted. However, this 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.

public put(uri: String, data: Array): Void

Issue a PUT request for the current uri.

Description
This call initiates a PUT request. If a contentLength has not been previously defined for this request, chunked transfer encoding will be enabled (See chunked).
Parameters
uri: String The uri to delete. This overrides any previously defined uri for the Http object.
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 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.

public read(buffer: ByteArray, offset: Number = 0 , count: Number = -1): Number

Read a block of response content data from the connection.

Parameters
buffer: ByteArray Destination byte array for the read data.
offset: Number Offset in the byte array to place the data. If offset is -1, data is appended at the current byte array write position. [default: 0 ]
count: Number Number of bytes to read. [default: -1]
Returns
A count of the bytes actually read. This call may return with fewer bytes read than requested. If a callback has been defined, this call will not block and may return zero if no data is currently available. If no callback has been defined, it will block.
Throws
IOError: if an I/O error occurs.

public readLines(count: Number = -1): Array

Read the request response as an array of lines.

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.

public readString(count: Number = -1): String

Read the request response as a string.

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.

public readXml(): XML

Read the request response as an XML document.

Returns
The response content as an XML object.
Throws
IOError: if an I/O error occurs.

public setCredentials(username: String, password: String): Void

Set the user credentials to use if the request requires authentication.


public trace(uri: String = null): Void

Issue a TRACE request for the current uri.

Description
Use readString to retrieve the response.
Parameters
uri: String New uri to use. This overrides any previously defined uri for the Http object. [default: null]
Throws
IOError: if the request cannot be issued to the remote server.

public upload(url: String, files: Object, fields: Object = null): Void

Upload files using multipart/mime.

Description
This routine initiates a POST request and sends the specified files and form fields using multipart mime encoding. This call also automatically enables chunked transfer encoding (See chunked).
Parameters
url: String The url 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)

public wait(timeout: Number = -1): Boolean

Wait for a request to complete.

Parameters
timeout: Number Time in milliseconds to wait for the request to complete. [default: -1]
Returns
True if the request successfully completes.

public write(data: Array): Void

Write body data to the request stream.

Description
The write call blocks while writing data. The Http.contentLength should normally be set prior to writing any data to ensure that the request "Content-length" header is properly defined. If the body length has not been defined, the data will be transferred using chunked transfers. In this case, you should call write() with no data to signify the end of the write stream. the Content-Length header will not be defined and the remote server will have to close the underling HTTP connection at the completion of the request. This will prevent HTTP keep-alive for subsequent requests.
Parameters
data: Array Data objects to write to the request stream. Data is written raw and is not encoded or converted. However, write intelligently handles arrays such that, each element of the array will be written. If encoding of write data is required, use the BinaryStream filter.
Throws
StateError: if the Http method is not set to POST. , IOError: if more post data is written than specified via the contentLength property.