Json-RPC概念
Json-RPC是基于Json格式远程过程调用规范。目前通用是2.0的规范
区别RPC
顾名思义,多了json这个前缀。先看下2者的示例格式,
Json-RPC通信的数据格式如下:
--> {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}
其中,关键字jsonrpc,method是固定的,也就是规范要求的。那么在一些实现的框架解析的时候,按此实现即可。
PRC格式:
struct call_body {
unsigned int rpcvers;
unsigned int prog;
unsigned int vers;
unsigned int proc;
opaque_auth cred;
opaque_auth verf;
1 parameter
2 parameter . . . };
同样,这个结构体的信息是固定不变的。实现RPC框架按此解析实现。比如hessian,RMI等。
2者的区别也是一目了然的。
1)传输数据格式不同。
2)实现框架的使用方法也不相同。
应用
在Java开发环境中,实现了该规范的框架有下面几种,jsonrpc4j、jpoxy、json-rpc。
2个方式调用都非常的简单。jsonrpc4j可以和spring完美兼容,我选择了它。
客户端代码如下:
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
public class client {
public void get(){
try {
JSONObject jsonObject = new JSONObject();
JSONObject jsonObject_While_List = new JSONObject();
JSONObject params = new JSONObject();
//params
params.put("PhoneNo", "911");
jsonObject_While_List.put("method", "QueryWhitePhone");
jsonObject_While_List.put("jsonrpc","2.0");
jsonObject_While_List.put("id",1);
jsonObject_While_List.put("params", params);
System.out.println(jsonObject_While_List.toString());
/*
try{
jsonObject.put("Sender","112233");
jsonObject.put("BCastType",0);
jsonObject.put("priority",2);
jsonObject.put("Volume",10);
jsonObject.put("ExpireIn",300);
jsonObject.put()
System.out.println(jsonObject.toString());
}catch (JSONException e){
e.printStackTrace();
}*/
JsonRpcHttpClient client = new JsonRpcHttpClient(new URL("http://192.168.1.142:5566/iob_device?SessionID=N4pO4ZzhRQOvISMgBB5VBjowOmFkbWluOjE="));
String res = client.invoke("Echo",params,String.class);
System.out.println(res);
}catch (java.lang.Exception e){
System.out.println(e);
}catch (java.lang.Throwable e){
System.out.println(e);
}
}
public static void main(String[] args){
client client = new client();
client.get();
}
}