JSON-RPC 2.0 Client
- Java library for creating client sessions
to remote JSON-RPC 2.0 services - Small and straightforward to use,
no fancy frameworks - Optional CORS, custom header and
self-signed certificate support
1. JSON-RPC 2.0 client sessions for Java
This Java library provides a simple class for establishing client sessions to JSON-RPC 2.0 servers.
- Create a new session to the desired JSON-RPC 2.0 server URL.
- Use the session object to send JSON-RPC 2.0 requests to the server and receive the corresponding responses. Sending of JSON-RPC 2.0 notifications is also supported.
The JSON-RPC 2.0 messages are transported with HTTP(S) POST.
Apart from the basic functionality - sending JSON-RPC 2.0 requests + notifications and receiving responses, this library also has a number of configuration options:
- Customise the "Content-Type" header in HTTP POST requests.
- Set an "Origin" header in HTTP POST requests to simulate Cross-Origin Resource Sharing (CORS) requests from a browser.
- Accept HTTP cookies, for JSON-RPC services that use this out-of-channel method for keeping track of user sessions.
- Customise the allowable "Content-Type" header values in HTTP POST responses.
- Set an HTTP proxy.
- Enable HTTP response compression using GZIP and DEFLATE content encoding.
- Preserve the parse order of JSON object members in JSON-RPC 2.0 response results (for human facing clients, such as the JSON-RPC 2.0 Shell ).
- Ignore version 2.0 checks when parsing responses to allow client sessions to older JSON-RPC (1.0) servers.
- Parse non-standard attributes in JSON-RPC 2.0 responses.
- Set timeouts for HTTP server connect and read operations.
- Trust all X.509 server certificates (for secure HTTPS connections), including self-signed certificates.
2. Requirements
- Supported JSON-RPC protocol version: 2.0
- JSON-RPC 2.0 transport mechanism: HTTP (POST)
- Java Runtime: 1.5+
- Package dependencies:
- JSON-RPC 2.0 Base for creating, serialising and parsing JSON-RPC 2.0 messages (also available on this web site, JAR included in the download package for convenience).
- JSON Smart for encoding and decoding JSON text (JAR included in the download package for convenience).
3. Installation
Place the downloaded jsonrpc2-client-{version}.jar
file as well as the
required jsonrpc2-base-{version}.jar
and json-smart-{version}.jar
dependencies in your Java CLASSPATH.
If you use Maven to build your project:
<dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>jsonrpc2-client</artifactId> <version>{version}</version> </dependency>
where {version} should be the latest stable.
4. Example
First, import the required packages:
// The Client sessions package import com.thetransactioncompany.jsonrpc2.client.*; // The Base package for representing JSON-RPC 2.0 messages import com.thetransactioncompany.jsonrpc2.*; // The JSON Smart package for JSON encoding/decoding (optional) import net.minidev.json.*; // For creating URLs import java.net.*;
Then, create a new session to a JSON-RPC 2.0 web service at a specified URL, e.g.
http://jsonrpc.example.com:8080
:
// The JSON-RPC 2.0 server URL URL serverURL = null; try { serverURL = new URL("http://jsonrpc.example.com:8080"); } catch (MalformedURLException e) { // handle exception... } // Create new JSON-RPC 2.0 client session JSONRPC2Session mySession = new JSONRPC2Session(serverURL);
Once the client session object is created, you can use to send a series of JSON-RPC 2.0 requests and notifications to it.
Sending an example getServerTime
request:
// Construct new request String method = "getServerTime"; int requestID = 0; JSONRPC2Request request = new JSONRPC2Request(method, requestID); // Send request JSONRPC2Response response = null; try { response = mySession.send(request); } catch (JSONRPC2SessionException e) { System.err.println(e.getMessage()); // handle exception... } // Print response result / error if (response.indicatesSuccess()) System.out.println(response.getResult()); else System.out.println(response.getError().getMessage());
The complete Java example can be downloaded from here.
5. Options
The JSON-RPC 2.0 client session options are handled by the
JSONRPC2SessionOptions
class.
Setting a custom
"Content-Type"
header in HTTP POST requests (the default is application/json
):
mySession.getOptions().setRequestContentType("application/json+rpc");
Setting an "Origin" header to simulate a CORS request from a browser:
mySession.getOptions().setOrigin("http://my-domain.com");
Turning on support for HTTP cookies, to accomodate, for example, JSON-RPC servers that use cookies for handling the user sessions:
mySession.getOptions().acceptCookies(true);
Changing the allowable "Content-Type" header values in HTTP POST responses (the default allowable are "application/json" and "text/plain"):
mySession.getOptions().setAllowedResponseContentTypes(new String[]{"application/json+rpc"});
To preserve the parse order of JSON object members in JSON-RPC 2.0 response results (may slow down performance a bit):
mySession.getOptions().preserveParseOrder(true);
To ignore JSON-RPC 2.0 version checking:
mySession.getOptions().ignoreVersion(true);
To parse non-standard attributes (such as meta or debugging fields) included in JSON-RPC 2.0 responses:
mySession.getOptions().parseNonStdAttributes(true);
To set specific timeouts (in milliseconds) for HTTP connect and read operations to the remote JSON-RPC 2.0 server:
mySession.getOptions().setConnectTimeout(3000); // 3 seconds mySession.getOptions().setReadTimeout(1000); // second
To set up an HTTP proxy:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 8080)); mySession.getOptions().setProxy(proxy);
To enable HTTP response compression using GZIP or DEFLATE content encoding (if the web server doesn't support compression this setting will have no effect):
mySession().getOptions().enableCompression(true);
To trust self-signed certificates presented by the JSON-RPC 2.0 server (for secure HTTPS connections; note: use only for testing and development purposes!):
mySession.getOptions().trustAllCerts(true);
6. Setting custom HTTP URL connection properties
The client library also supports a mechanism to configure the underlying
HttpURLConnection
objects before the actual connections are established.
You may need this to set custom HTTP request properties such as
- headers,
- cookies,
- and timeouts.
To do this implement a
ConnectionConfigurator
and
pass it
to the JSONRPC2Session
class.
Your connection configurator will be called after the session options are
applied and before establishing the actual HTTP connection.
Example custom configurator to set HTTP basic authentication:
import com.thetransactioncompany.jsonrpc2.client.ConnectionConfigurator; public class BasicAuthenticator implements ConnectionConfigurator { public void configure(HttpURLConnection connection) { // add custom HTTP header connection.addRequestProperty("Authorization", "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); } }
Applying the configurator to your JSON-RPC 2.0 session:
JSONRPC2Session session = new JSONRPC2Session(...); session.setConnectionConfigurator(new BasicAuthenticator());
7. Inspecting the raw HTTP responses
For client applications that need to access specific headers or the raw content (e.g. for debugging purposes) of the HTTP response to a JSON-RPC 2.0 request or notification there is a dedicated inspection interface.
import com.thetransactioncompany.jsonrpc2.client.RawResponse; import com.thetransactioncompany.jsonrpc2.client.RawResponseInspector; public class MyInspector implements RawResponseInspector { public void inspect(RawResponse response) { // print the HTTP status code System.out.println("HTTP status: " + response.getStatusCode()); // print the value of the "Date" HTTP header System.out.println("Date: " + response.getHeaderField("Date")); } }
Configuring the JSON-RPC 2.0 session object to invoke the inspector every time when a HTTP response is received:
JSONRPC2Session session = new JSONRPC2Session(...); session.setRawResponseInspector(new MyInspector());
8. JavaDoc documentation
The JSON-RPC 2.0 Client source comes with rich documentation in the form of JavaDocs. A copy of the docs is available for browsing online.
9. Download
The JSON-RPC 2.0 Client package is offered with an Apache 2.0 open source license.
JSON-RPC 2.0 ClientGet in touch with me if you have questions or comments about the JSON-RPC 2.0 Server software. For general questions go to the JSON-RPC forum.
You may also want to have a look at the companion JSON-RPC 2.0 Shell product, a must have tool for developers undertaking serious JSON-RPC 2.0 work.
10. Change log
- version 1.0 (2010-11-09)
- First release.
- version 1.1 (2011-03-10)
- Major refactoring and API change.
- Adds optional setting for custom "Content-Type" header in HTTP POST requests.
- Adds optional setting to customise the allowable "Content-Type" header values in HTTP POST responses.
- Adds optional setting to disable strict JSON-RPC 2.0 parsing of responses to allow sessions with older JSON-RPC (1.0) servers.
- Adds optional setting to trust self-signed server sertificates for secure HTTPS connections.
- version 1.2 (2011-03-29)
- Skips ID match checking for JSON-RPC 2.0 responses indicating errors -32700 (parse error), -32600 (invalid request) and -32603 (internal error).
- version 1.3 (2011-07-11)
- Raises minimal JSON-RPC 2.0 Base requirement to version 1.19.
- Deprecates JSONRPC2Session.disableStrictParsing() in favour of JSONRPC2Session.ignoreVersion().
- Deprecates JSONRPC2Session.strictParsingDisabled() in favour of JSONRPC2Session.ignoresVersion().
- Adds option to parse non-standard attributes appended to JSON-RPC 2.0 responses.
- version 1.4 (2011-07-13)
- Moves all optional session properties and methods into a separate JSONPRC2SessionOptions class.
- Adds a JUnit test for the JSONRPC2SessionOptions class.
- version 1.5 (2011-07-18)
- Adds an interface for specifying a custom HTTP URL connection configurator.
- version 1.6 (2011-08-23)
- Adds an interface and class for inspecting the raw HTTP response.
- Adds a configuration option to accept HTTP cookies.
- version 1.7 (2012-02-16)
- Provides additional JSON-RPC 2.0 session exception cause types.
- version 1.7.1 (2012-04-03)
- Updates JSON-RPC 2.0 Base JAR to 1.25.1 (JSON Smart 1.1.1).
- version 1.7.2 (2012-07-14)
- Updates JSON-RPC 2.0 Base JAR to 1.27.
- version 1.8 (2012-08-26)
- Introduces option for controlling HTTP connection and read timeouts.
- version 1.9 (2012-12-01)
- Upgrades JSON-RPC 2.0 Base JAR to 1.30.
- version 1.10 (2012-12-13)
- Adds HTTP proxy support.
- version 1.11 (2012-12-28)
- Fixes JSONRPC2SessionException message on missing Content-Type header in HTTP response.
- Upgrades JSON-RPC 2.0 Base JAR to 1.31.
- version 1.12 (2013-01-22)
- Adds support for HTTP response compression using GZIP and DEFLATE content encoding.
- Switches cookie handling to java.net.CookieManager to add support for cookie replacement and expiration.
- version 1.13 (2013-03-18)
- Forces UTF-8 output for POSTed JSON-RPC 2.0 strings.
- version 1.14 (2013-03-29)
- Switches project build from Ant to Maven.
- Expects UTF-8 input for HTTP responses.
- Upgrades to JSON-RPC 2.0 Base 1.34.
- version 1.14.1 (2013-03-30)
- Updates Maven pom.xml.
- version 1.14.2 (2013-03-30)
- Fixes bug in assembly-dist.xml.
- version 1.14.3 (2013-04-02)
- Publishes library to Maven Central.
- version 1.14.4 (2013-06-13)
- Fixes exception reporting on request / response ID mismatch.
- version 1.15 (2015-03-16)
- Cleans up code.
- Upgrades to JSON-RPC 2.0 Base 1.36.
- Upgrades to JSON Smart 1.3.1.