HTTP Client Library
Contents
Easily access remote web API’s and data sources over HTTP using this library.
To start using this library, add the following into your build.gradle
file:
dependencies {
include 'com.enonic.lib:lib-http-client:3.2.1'
}
Usage
To use this library in your JavaScript code, it first needs to be required:
const httpClient = require('/lib/http-client');
To make an HTTP or HTTPS request just call the request
function with the desired parameters.
const response = httpClient.request({
url: 'http://somehost/my/service', (1)
method: 'POST', (2)
headers: {
'Cache-Control': 'no-cache' (3)
},
connectionTimeout: 20000, (4)
readTimeout: 5000, (5)
body: '{"id": 123}', (6)
contentType: 'application/json' (7)
});
1 | The target URL for the request. Should be a valid http:// or https:// URL. |
2 | The HTTP method, if omitted the GET method will be used. |
3 | Optional request headers can be specified. |
4 | Maximum time (ms) to wait for the connection to be established. |
5 | Maximum time (ms) to wait for the server to send back data. |
6 | The body of the HTTP request. |
7 | The content type of the request. |
The function will return an object with the properties of the HTTP response:
response = {
'status': 200, (1)
'message': 'OK', (2)
'body': 'Response contents', (3)
'contentType': 'text/plain', (4)
'headers': {
'Content-Length': '17', (5)
'content-type': 'text/plain'
}
};
1 | HTTP status code. |
2 | HTTP status message. |
3 | Contents of the body if it’s text. For binary contents see bodyStream property below. |
4 | Content type of the response. |
5 | Response HTTP headers. |
API
The following function is defined in this library.
request(options)
Sends an HTTP request and returns the response received from the remote server. The request is made synchronously, that means the execution will block until the response is received.
Parameters
The request function takes a parameter object with options. The only mandatory option is the url
.
-
options
(object) Parameters to make the HTTP request.-
url
(string) URL to which the request is sent. -
method
(string) The HTTP method to use for the request (e.g. "POST", "GET", "HEAD", "PUT", "DELETE", "PATCH"). The default value is"GET"
. -
queryParams
(object) Query parameters to be sent with the request. -
params
(object) Form parameters to be sent with the request. Will not be used ifqueryParams
is provided. -
headers
(object) HTTP headers, an object where the keys are header names and the values the header values. -
disableHttp2
(boolean) Disable use of HTTP/2 protocol. The default value isfalse
. For insecure HTTP connections HTTP/2 is always disabled. (added in v3.2.0) -
connectionTimeout
(number) The timeout on establishing the connection, in milliseconds. The default value is10000
. -
readTimeout
(number) The timeout on waiting to receive data, in milliseconds. The default value is10000
. -
body
(string | object) Body content to send with the request, usually for POST or PUT requests. It can be of type string or stream. -
contentType
(string) Content type of the request. -
followRedirects
(boolean) If set tofalse
, redirect responses (status=3xx
) will not trigger a new internal request, and the function will return directly with the3xx
status. Iftrue
, redirects will be handled internally. Default is to handle redirects internally, but don’t redirect from https to http. -
multipart
(object[]) Multipart form data to send with the request, an array of part objects. Each part object contains 'name', 'value', and optionally 'fileName' and 'contentType' properties. Where 'value' can be either a string or a Stream object. -
auth
(object) Settings for basic authentication.-
user
(string) User name for basic authentication. -
password
(string) Password for basic authentication.
-
-
proxy
(object) Proxy settings.-
host
(string) Proxy host name or IP address to use. -
port
(number) Proxy port to use. -
user
(string) User name for proxy authentication. -
password
(string) Password for proxy authentication.
-
-
certificates
(*) Stream of PEM encoded certificates. Replaces the host platform’s certificate authorities with a custom certificate. -
clientCertificate
(*) Stream of PEM encoded certificate: Private key (in PKCS #8 format) and the client certificate concatenated.
-
For every new combination of connectionTimeout , followRedirects , auth. , proxy. , certificates , clientCertificate a new internal HttpClient gets created. |
Returns
The function will return a response
object with the following properties:
-
status
(number) HTTP status code returned. -
message
(string) HTTP status message returned. -
headers
(object) HTTP headers of the response. -
cookies
(object) Array of HTTP cookies set in the response. -
contentType
(string) Content type of the response. -
body
(string) Body of the response as string. Null if the response content-type is not of type text. -
bodyStream
(object) Body of the response as a stream object.
KeyStore and TrustStore Configuration [v3.0.0+]
Use JVM system properties to configure KeyStore and TrustSore: https://docs.oracle.com/en/java/javase/11/security/java-secure-socket-extension-jsse-reference-guide.html#GUID-7D9F43B8-AABF-4C5B-93E6-3AFB18B66150
If certificates is specified, library does not use default KeyStore for identity material. Either specify both certificates and clientCertificate or leave both undefined to use Default Keystore and Truststore. |
Compression
The Library supports transparent gzip
and deflate
response body decompression. Accept-Encoding
header is set by library and should not be provided in headers via API.
Examples
Basic Authentication
const httpClient = require('/lib/http-client');
const response = httpClient.request({
url: 'http://somehost/protected/service',
method: 'GET',
auth: {
user: 'username',
password: 'secret'
}
});
Request via Proxy
const httpClient = require('/lib/http-client');
const response = httpClient.request({
url: 'http://somehost/some/service',
method: 'GET',
proxy: {
host: '172.16.0.42',
port: 8080,
user: 'admin',
password: 'secret'
}
});
Multipart POST request
const httpClient = require('/lib/http-client');
const response = httpClient.request({
url: 'http://somehost/uploadMedia',
method: 'POST',
contentType: 'multipart/mixed',
multipart: [
{
name: 'media',
fileName: 'logo.png',
contentType: 'image/png',
value: myImageStream
},
{
name: 'category',
value: 'images'
}
]
});
Using custom certificate
const httpClient = require('/lib/http-client');
const ioLib = require('/lib/xp/io'); // IO API library from XP
const token = app.config['token']; // Token stored in the application config file
const certificates = ioLib.newStream(app.config['certificates']); // Certificate stored in the application config file. NOTE: It is not a location of the certificate file, but body of the certificate itself.
const response = httpClient.request({
url: 'http://somehost/some/service',
method: 'POST',
headers: {'Authorization': 'Bearer ' + token},
contentType: 'application/json',
certificates: certificates
});
Compatibility
-
This library is not compatible with XP releases before version 7.0. Make sure you reference the lib as
/lib/http-client
and not as/lib/xp/http-client
or/site/lib/xp/http-client
. -
Starting from version 3.0.0 library Uses Java HttpClient instead of OkHttp Client. It may introduce a few minor incompatibilities. For instance, Default User-Agent is now JVM vendor dependent.
-
Starting from version 3.0.0 library does not support Preemptive authentication. Use
Authorization: Basic <credentials>
header instead. -
Starting from version 3.0.0 library uses Java Platform KeyStore. It is JVM vendor specific but in most cases it is specified by
javax.net.ssl.keyStore
system property. KeyStore Configuration is no longer applicable andclientCertificate
can only be typeof Stream.