HTTPRequest and HTTPResponse Objects
HTTPRequest objects are used to either send a HTTP or HTTPS request to a web server, or to obtain information about the HTTP request in a servlet or server page.
As of the 0.7.0 release, the HTTPRequest object has been moved into a separate net module, available through the com.appinf.osp.js.net bundle.
You'll have to import the net module in your script before being able to use the HTTPRequest object.
To send a HTTP request, create a new HTTPRequest object, using the HTTPRequest constructor function. The constructor takes three optional arguments, a request method (e.g., "GET"), a URI (e.g., "https://macchina.io") and the HTTP version string (e.g., "HTTP/1.1"). All these values can be set at a later time as well, via properties.
HTTP requests can be sent in blocking or asynchronous mode. In blocking mode, the script has to wait until the HTTP request completes. In asynchronous mode, the HTTP request is sent in a separate thread, and the script is notified of the result via a callback function.
Here is an example for a synchronous request:
const net = require('net'); let request = new net.HTTPRequest('GET', 'https://macchina.io'); let response = request.send(); logger.information(response.status, " ", response.reason); logger.information(response.contentType); logger.information(response.content);
And here's the same example, with the request sent asynchronously:
const net = require('net'); let request = new net.HTTPRequest('GET', 'https://macchina.io'); let response = request.send( function (result) { if (result.error) { logger.error(result.error); } else { logger.information(result.response.status, " ", result.response.reason); logger.information(result.response.contentType); logger.information(result.response.content); } } );
Of course, HTTPRequest can also be used to send POST or PUT requests, as well as requests using any other HTTP methods.
Here's a sample how to post some JSON to a Hue base station to control a smart bulb:
const net = require('net'); const request = new net.HTTPRequest('PUT', 'http://192.168.178.151/api/newdeveloper/lights/1/state'); request.content = JSON.stringify({on: true, bri: 100, hue: 46920, sat: 255}); request.contentType = 'application/json'; request.timeout = 10.0; request.send( function(result) { if (result.error) { logger.error(result.error); } else { logger.information(result.response.status, " ", result.response.reason); } } );
HTTPRequest Properties
HTTPRequest objects support the following properties:
method (r/w)
The request method, e.g. "GET", "POST", etc.
uri (r/w)
The request URI or path, e.g. "/index.html".
version (r/w)
The HTTP version string, usually "HTTP/1.1".
contentType (r/w)
The request content type, e.g. "application/json".
content (r/w)
The request content, as string.
Only Unicode UTF-8 encoded text content is supported. For other types of content, use the buffer property.
buffer (r/w)
The request content, as Buffer object. Using the buffer property, content that is not UTF-8 text can be handled.
Note: setting the buffer property will also affect the content property (and vice-versa), since both use the same underlying data.
timeout (r/w)
The request timeout in seconds.
cookies (ro)
An object containing all cookies sent with the request, with cookie name as key and cookie value as string value.
headers (ro)
An object containing all header fields as properties. Note that the returned object is not kept in sync with the request object. After making changes to the headers in the request object headers (by calling set), query this property again to receive an updated object.
parameters (r/w)
An object containing form parameters to be sent with the request. Works with GET and POST requests. Example:
let request = net.HTTPRequest.post('https://1.2.3.4/login'); request.parameters = { username: 'janedoe', password: 's3cr3t' }; let response = request.send();
credentials (ro)
If the request has been sent with HTTP Basic Authentication information, returns an object with a "username" and a "password" property containing the credentials.
If no valid authentication information has been sent, returns null.
HTTPRequest Methods
The following methods are supported by HTTPRequest objects:
has(name)
Returns true if the request has a header with the given name, false otherwise.
get(name [, default])
Returns the value of the request header with the given name, or the given default value if the header is not present. If no default is given, returns an empty string if the header is not present.
set(name, value)
Sets the request header with the given name to the given value.
authenticate(username, password)
Adds a HTTP Basic Authentication header to the request, using the given credentials.
send([callback])
Sends the request. If a callback function is given, the function will return immediately and will not return anything. Success or failure will be reported via the callback function. The callback function must accept a single argument, which will be an object containing an "error" or a "response" property. If the request failed, the "error" property will contain an error message. Otherwise, the "response" property will contain a HTTPResponse object. Note that even if no "error" property is set, the request may still have failed, although on the HTTP level. Check the HTTP response status, using the result.response.status property.
If no callback function is given, the request is sent and the function will block until the complete response is received, or an error has occurred. If an error occurred, an exception will be raised. Otherwise, a HTTPResponse object will be returned.
cancel()
Cancels an asynchronous request. Processing of the request will end and the callback function passed to send() will not be called.
If cancel() is called after the request has already been completed, and the callback function has been called, nothing happens.
HTTPResponse Properties
HTTPResponse object support the following properties:
status (r/w)
The HTTP status code, e.g. 200.
reason (r/w)
The HTTP status message, e.g. "OK" (for a 200 status).
version (r/w)
The HTTP version string, e.g. "HTTP/1.1".
contentType
The response body content type, e.g. "text/html".
content (r/w)
The response content, as string.
Only Unicode UTF-8 encoded text content is supported. For other types of content, use the buffer property.
buffer (r/w)
The response content, as Buffer object. Using the buffer property, content that is not UTF-8 text can be handled.
Note: setting the buffer property will also affect the content property (and vice-versa), since both use the same underlying data.
headers (ro)
An object containing all header fields as properties. Note that the returned object is not kept in sync with the response object. After making changes to the headers in the response object headers (by calling set), query this property again to receive an updated object.
HTTPResponse Methods
has(name)
Returns true if the response has a header with the given name, false otherwise.
get(name [, default])
Returns the value of the response header with the given name, or the given default value if the header is not present. If no default is given, returns an empty string if the header is not present.
set(name, value)
Sets the response header with the given name to the given value.
setStatus(status)
Sets the response status code, e.g. 200.
write(text) and writeln(text)
Appends text to the response body.
Note: currently only Unicode UTF-8 encoded text content is supported.
writeln() adds a newline after the text.
writeHTML(text)
Writes text to the response body. All HTML reserved characters will be escaped properly.
htmlize(text)
Returns a copy of text with all HTML reserved characters properly escaped.
send()
Sends the response. Can be used in servlets or server pages on the global response object only.
sendFile(path [, contentType])
Sends the file given by path in the response, using the given contentType. If no contentType is given, uses the one from the contentType property.
redirect(location [, status])
Sends a redirect response with the given location in the Location header. If no status is given, a 302 Found status is sent in the response, otherwise the given status is used, which must be a valid 30x redirect status:
- 301 (Moved Permanently)
- 302 (Found)
- 303 (See Other)
- 307 (Temporary Redirect)
- 308 (Permanent Redirect)
The form Object
The global form object is available in servlets and server pages. It gives convenient access to any HTML form data sent by the browser.
The form object has two methods, has() and get().
Additionally, the form object has shortcut accessors for form fields. Instead of writing:
const value = form.get('field');
one can also write:
const value = form.field;
form Methods
has(name)
Returns true if the form has a field with the given name, false otherwise.
get(name [, default])
Returns the value of the form field with the given name. If the field is not present, returns the default value. If no default value has been given, returns an empty string if the form field does not exist.
form Properties
fields
This read-only property returns an object containing all form fields and their values as properties.
The uploads Array
The global uploads array is available in servlets and server pages. It gives convenient access to any files uploaded through the browser via a HTML form (with encoding type multipart/form-data).
For every file uploaded, the uploads array has an object providing information about the file. The properties supported by these objects are described below.
Uploaded files can be accessed using the using the File API.
It is possible to specify a maximum size for uploaded files (in bytes), as well as the maximum number of files uploaded with a single request in the bundle.properties of the bundle containing the servlet or server page, with the osp.js.maxUploadSize and osp.js.maxUploadCount properties e.g.:
osp.js.maxUploadSize = 262144 osp.js.maxUploadCount = 1
The default maximum upload size is 2 MBytes per file. If an uploaded file exdeeds the specified maximum size, it will be ignored and a warning message will be written to the console. The default maximum upload count is 4. If the number of uploaded files exceeds the specified maximum count, these files will be ignored and a warning message will be printed to the console.
Note that uploaded files will be automatically deleted after the servlet or server page finishes processing. If a servlet or server page wants to keep an uploaded file, it should move or copy it to a different location, using the File API.
upload Properties
path
The full path on the local filesystem the file has been stored to. The uploaded file will be stored in the system's temporary file directory, and will have a random unique file name.
name
The name of the form element the file was uploaded through.
filename
The original name of the uploaded file.
contentType
The MIME type of the uploaded file, as reported by the browser in the part's Content-Type header.
size
The size of the uploaded file in bytes.
headers
An object containing all part headers for the uploaded file sent by the browser, e.g. Content-Type and Content-Disposition.
The session Object
The global session object is available in servlets and server pages. It gives access to the session object for the current request.
Note: Currently there is no way to create a session object from JavaScript. In macchina.io EDGE, a session object is created when a user logs in to the web interface.
session Properties
The session object supports the following read-only properties:
id
The internal ID of the session object.
username
The name of the signed-in user. Only available if a user is signed in and the session is authenticated.
authenticated
Returns true if the session is authenticated, otherwise false. A session is authenticated if the user has successfully signed in.
csrfToken
A random string that can be used as a CSRF synchronizer token in forms, to prevent CSRF (Cross-Site Request Forgery) attacks.
clientAddress
The IP address and port number of the HTTP client.
session Methods
setInt(name, integer)
Adds or updates a an integer property with the given name to the session.
getInt(name [, default])
Returns the integer value of the property with the given name.
setBool(name, boolean)
Adds or updates a boolean property with the given name to the session.
getBool(name [, default])
Returns the boolean value of the property with the given name.
setString(name, string)
Adds or updates a string property with the given name to the session.
getString(name [, default])
Returns the string value of the property with the given name.
erase(name)
Erases the property with the given name.
authorize(permission)
Returns true if the currently signed in user has the given permission, by checking with the OSP authentication service, using the username from the session.