HTTP-RPC 5.7 Released

HTTP-RPC version 5.7 is now available for download and via Maven Central. Among other enhancements, this release adds support for consuming REST services in JavaScript via the Nashorn scripting engine.

In a previous update, I showed how HTTP-RPC’s WebServiceProxy class can be used to access the operations of a simple math service:

// GET /math/sum?a=2&b=4
WebServiceProxy webServiceProxy = new WebServiceProxy("GET", new URL("http://localhost:8080/httprpc-test/math/sum"));

HashMap arguments = new HashMap();

arguments.put("a", 4);
arguments.put("b", 2);

webServiceProxy.setArguments(arguments);

System.out.println(webServiceProxy.invoke()); // 6.0
// GET /math/sum?values=1&values=2&values=3
WebServiceProxy webServiceProxy = new WebServiceProxy("GET", new URL("http://localhost:8080/httprpc-test/math/sum"));

HashMap arguments = new HashMap();

arguments.put("values", Arrays.asList(1, 2, 3));

webServiceProxy.setArguments(arguments);

System.out.println(webServiceProxy.invoke()); // 6.0

The following example demonstrates how the same operations can be invoked from JavaScript:

var webServiceProxy = new org.httprpc.WebServiceProxy("GET", new java.net.URL("http://localhost:8080/httprpc-test/math/sum"));

// GET /math/sum?a=2&b=4
webServiceProxy.arguments = {"a": 4, "b": 2};

print(webServiceProxy.invoke()); // 6

// GET /math/sum?values=1&values=2&values=3
webServiceProxy.arguments = {"values": Java.asJSONCompatible([1, 2, 3])};

print(webServiceProxy.invoke()); // 6

Note that, because Nashorn automatically translates Java List and Map values to JavaScript array and object instances respectively, transformation or adaptation of service responses is not generally necessary. For example, the following script would print the third value in the Fibonacci sequence:

var webServiceProxy = new org.httprpc.WebServiceProxy("GET", new java.net.URL("http://localhost:8080/httprpc-test/test/fibonacci"));

// [1, 2, 3, 5, 8, 13]
var fibonacci = webServiceProxy.invoke();

print(fibonacci[2]); // 3

For more information, see the project README.