The ease with which the code samples worked for the below helloworld-ish sample, motivated me to write about it. JSON-RPC is simpler to debug and implement than SOAP and can be secured by implementing it over https. Most of the time in systems integration all we need is getting the .NET software to communicate with the Java software and in such simpler scenarios where RPC mechanism which is firewall friendly like SOAP is needed then thats where JSON-RPC is a good option.
helloworld.ashx - the JSONRPCHandler
using System;
using System.Web;
using Jayrock.Json;
using Jayrock.JsonRpc;
using Jayrock.JsonRpc.Web;
namespace jayrockserv
{
public class HelloWorld : JsonRpcHandler
{
[JsonRpcMethod("greetings")]
public string Greetings()
{
return "Welcome to Jayrock!";
}
[JsonRpcMethod("add")]
public int sum(int a, int b)
{
return (a+b);
}
}
}
The Java JSON-RPC client:
Main.java:
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codebistro.jsonrpc.Client;
import org.codebistro.jsonrpc.HTTPSession;
import org.codebistro.jsonrpc.TransportRegistry;
public class Main {
private static final Log log = LogFactory.getLog(Main.class);
private static final String rootURL= "http://localhost/jayrock/helloworld.ashx";
/**
* @param args
*/
public static void main(String[] args) {
// Register HTTP
HTTPSession.register(TransportRegistry.i());
HTTPSession httpSession= (HTTPSession)TransportRegistry.i().createSession(rootURL);
HttpState state= new HttpState();
httpSession.setState(state);
Client client= new Client(httpSession);
RpcIF rpc = client.openProxy(null, RpcIF.class);
String str = rpc.greetings();
log.debug("Output:" + str);
}
}
RpcIF.java:
public interface RpcIF {
String greetings();
}
O/P on client side:
JSON RPC REQUEST ==> {"id":1,"method":"greetings","params":[]}
JSON RPC RESPONSE ==> {"id":1,"result":"Welcome to Jayrock!"}
No comments:
Post a Comment