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.

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:

2. Requirements

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

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.

Download now JSON-RPC 2.0 Client

Get 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