04. HTTP
The http object is a built-in object that provides HTTP client functionality.
Functional overview:
- Provides the HTTP client function.
- Supports HTTP v1.1.
Limitations:
- The number of HTTP session resources that can be used simultaneously is
2
.
Note that both http and https objects share this resource. - Resource errors cause exceptions.
http Global Object
Methods()/Properties | Summary | Version | Note |
---|---|---|---|
http.request() | Starts HTTP communication. | {ClientRequest} and {IncomingMessage} instances are generated. |
Details
http.request(options[,callback][,sockTo])
Starts HTTP communication.
Name | Type | M/O | Summary | Note |
---|---|---|---|---|
options | Object | mandatory | HTTP communication options Refer to options for details. | This argument is required. |
callback(res) | function | optional | Executes the callback process when the response header is received. The following arguments are attached. res : {IncomingMessage} An instance of {IncomingMessage} | Required when receiving data. |
sockTo | number | optional | Session timeout value [ms] (Up to 4,294,967,295 ms can be specified. Any value exceeding the maximum will be set to maximum.) The default value is 90000. | If specified, the session will be destroyed on timeout and notified by the error event. |
return | {ClientRequest} | - | {ClientRequest} : Generated {ClientRequest} | If resources are insufficient or parameters are abnormal, an exception occurs. |
options
Unset elements will be set with default values.
Name | Type | M/O | Summary | Note |
---|---|---|---|---|
host | string | optional | Domain name or IP address of the HTTP server The default value is '127.0.0.1'. | An exception will be raised if the number of characters exceeds 127 bytes. |
port | number | optional | Port number of the HTTP server The default value is '80'. | |
method | string | optional | Method name Specify one of 'GET', 'POST', 'PUT', 'HEAD'. The default value is 'GET'. | |
path | string | optional | Request path The default value is '/'. | |
headers | Object | optional | Request header Specify an object that contains any request header. This parameter is optional. Therefore, it does not have a default value. |
{ClientRequest}
This object is generated internally and returned by http.request().
Methods()/Properties | Summary | Version | Note |
---|---|---|---|
.on() | Registers an event handler. | ||
.write() | Sends data. | ||
.end() | Complete the HTTP-request. | ||
.abort() | HTTP-request transmission/HTTP-response reception is forcibly stopped. | ||
.errCode | Error code |
Details
.on(event,callback)
Registers an event handler.
Name | Type | M/O | Summary | Note |
---|---|---|---|---|
event | string | mandatory | Event name Names that can be used are: error | |
callback() | function | mandatory | Executes callback processing when an event occurs. | |
return | undefined | - | - |
event : ’error’
Executes callback when an error occurs during the HTTP-request.
The error can refer to the error code (.errCode) during or after callback execution.
.write(data[,callback])
Sends data.
Data is sent as Request-Body. Executes callback processing when transmission is completed.
Name | Type | M/O | Summary | Note |
---|---|---|---|---|
data | string, ArrayBuffer | mandatory | Transmission data | Divided writing is possible by cooperating with callback processing. The data size to be written at once should be 4KB or less. If an error occurs, reduce the data size to be written at one time. |
callback() | function | optional | Executes callback processing when transmission of write data is completed. | |
return | undefined | - | - |
.end([data][,callback])
If data exists, it is sent at Request-Body and completes the HTTP-request.
Executes callback processing when transmission of request data is completed.
This method is required when completing an HTTP-request.
Name | Type | M/O | Summary | Note |
---|---|---|---|---|
data | string, ArrayBuffer | optional | Transmission data | The data size to be written should be 4KB or less. If an error occurs, reduce the data size to be written and execute divided writing using .write(). |
callback() | function | optional | Executes the callback process when the write data has been transmitted. | |
return | undefined | - | - |
Usually, it is used as follows.
request.write('Hello World');
request.end();
The following is a sample of divided writing.
var WRITE_CHUNK = 1024;
var getBodyStream = function() {
var buff;
//...
//Prepare data up to WRITE_CHUNK.
//If there is no more data, return null.
//...
return buff; //{string}/{arrayBuffer}/null
};
var writeBodyStream = function() {
var buff = getBodyStream();
if(buff != null) {
print('request stream write!!!');
request.write(buff, writeBodyStream);
} else {
request.end(function() {
print('request stream end!!!');
});
}
}
writeBodyStream();
.abort()
HTTP-request transmission/HTTP-response reception is forcibly stopped.
This function triggers the call of the error event.
Name | Type | M/O | Summary | Note |
---|---|---|---|---|
return | undefined | - | - |
.errCode
Returns error code. This property has a value of type number
.
The following is the meaning of each value. It can be referenced in the callback of the error or later.
Error code | Summary |
---|---|
0 | No error |
1 | Aborted by calling .abort() |
2 | Parameter error |
3 | Resource error |
4 | Callback processing error |
5 | Socket timeout |
6 | Cancel due to sleep transition |
103 | Request-Body shortage error |
104 | Request-Body error |
115 | Socket error |
{IncomingMessage}
This object is generated internally by http.request() and returned as an argument of the callback process.
The received response header can be referenced when this object is returned.
Methods()/Properties | Summary | Version | Note |
---|---|---|---|
.on() | Registers an event handler. | ||
.read() | Reads Response-Body. | ||
.readBin() | Reads Response-Body in binary format. | ||
.statusCode | Status code on the status line of the HTTP response frame | ||
.statusMessage | Status message on the status line of the HTTP response frame | ||
.headers | HTTP response frame header |
Details
.on(event,callback)
Registers an event handler.
Name | Type | M/O | Summary | Note |
---|---|---|---|---|
event | string | mandatory | Event name Names that can be used are: error, readable, end | |
callback() | function | mandatory | Executes callback processing when an event occurs. | |
return | undefined | - | - |
event : ’error’
Executes the callback process when the reception of HTTP response is not completed.
At the same time, it is reflected in the error event of {ClientRequest}.
event : ’readable’
Executes callback processing when data exists in the reception buffer for HTTP-response.
When receiving data, this event must be handled.
Note that this readable event does not occur, and the end event may occur directly.
event : ’end’
Executes the callback process when the reception of HTTP-response is completed.
When receiving data, this event must be handled.
.read()
Reads Response-Body.
Name | Type | M/O | Summary | Note |
---|---|---|---|---|
return | string, null | - | Read Response-Body data | If it does not exist, null is returned. |
.readBin()
Reads Response-Body in binary format.
Name | Type | M/O | Summary | Note |
---|---|---|---|---|
return | ArrayBuffer, null | - | Read Response-Body data | If it does not exist, null is returned. |
This is a sample to read a character string in binary.
res.on('end', function() {
r_data = res.readBin();
r_data_u8 = new Uint8Array(r_data);
var s = '';
for(n=0; n<r_data_u8.length; n++) {
s += r_data_u8[n].toString();
}
print('body:' + s);
});
.statusCode
This property has a value of type number
.
You can refer to the status code on the status line of the HTTP response frame.
.statusMessage
This property has a value of type number
.
You can refer to the status message on the status line of the HTTP response frame.
.headers
This property has a value of type Object
.
You can refer to the header of the HTTP response frame. The header name becomes the property name.
For example, to obtain the value of the 'Date' header from the response header, do the following:
http.request(options, function(res) {
print(res.headers['Date']);
});
Object Usage Examples
Sample 1
This is a sample of the GET method. Reads data in a divided manner.
var HEADERS = {};
var options = {method: 'GET', host: '192.168.1.1', port: 80, path: '/test.txt', headers: HEADERS};
var request = http.request(options, function(res) {
print(res.statusCode);
print(this.statusMessage);
res.on('error', function() {
print('response error!');
});
res.on('readable', function() {
print(res.read());
});
res.on('end', function() {
print(res.read());
print('response complete!');
});
});
request.on('error', function() {
print('errCode=' + request.errCode);
});
request.end(function() {
print('request done!!!');
});
Sample 2
This is a sample of the POST method. Send "Hello World".
var BODY = 'Hello World';
var HEADERS = {'Content-Type': 'text/plain', 'Content-Length': BODY.length.toString()};
var options = {method: 'POST', host: '192.168.1.1', port: 80, path: '/post', headers: HEADERS};
var request = http.request(options, function(res) {
print(res.statusCode);
print(this.statusMessage);
res.on('error', function() {
print('response error!');
});
res.on('end', function() {
print('response complete!');
});
});
request.on('error', function() {
print('errCode=' + request.errCode);
});
request.end(BODY, function() {
print('request done!!!');
});