First, Jsonrpc introduction
Json-rpc is a cross language remote invocation protocol based on JSON, which is smaller than XML-RPC, webservice and other text-based protocols, and relatively hessian, JAVA-RPC and other binary protocols are easy to debug, implement, and extend, which is a very good remote calling protocol. At present, the mainstream language has a JSON-RPC implementation framework, the Java language in the better JSON-RPC implementation Framework has jsonrpc4j, Jpoxy, Json-rpc. Among the three, jsonrpc4j can be used independently and seamlessly assembled with spring, which is more suitable for project development based on spring.
Second, Jsonrpc simple description 1, the JSON format of the call
The data format is transmitted to the server side as follows:
{' Methods ': ' Method name ', ' params ': [' parameter array '], ' ID ': Method ID}
Description
First parameter: Is the method's name value pair
Second parameter: is a parameter array
Third parameter: is the method ID (optionally fill in)
Example: {"method": "DoSomething", "params": [], "id": 1234}
DoSomething is the method of the remote object, [] indicates that the parameter is null 2, the output JSON format
{
"Jsonrpc": "2.0",
"id": "1234",
"Result": null
}
three, Jsonrpc's demo
Here is a demo, the main content of this demo is to create a server-side object, called by the client
Object relationships
The object diagram is as follows:
3.1 Construction
1 Create a Web PROJCCT project
2 Create corresponding class, copy the jar package needed in Lib
3) Publish and run Tomcat
Publish the MyEclipse Tomcat environment, the most important is the Web.xml file, the following show Web.xml content
Note: The last URL, in "Host: Port" followed by the project name, and then the Url-pattern
The above diagram is an example: HTTP://127.0.0.1:8080/STUDYJSONRPC4J/RPC
3.2 Code
1) Entity class
Helloworldservice.java
Package com.cwqsolo.demo.enitity;
* * Defines the interface of a
service
/public interface HelloWorldService {public
helloworldbean Getdemobean (String code, String msg);
Public integer getInt (integer code);
public string getString (string msg);
public void dosomething ();
}
Helloworldbean.java
Package com.cwqsolo.demo.enitity;
Import java.io.Serializable;
public class Helloworldbean implements serializable{
private static final long serialversionuid = -12345l;
private int code;
Private String msg;
public int GetCode () {return
code;
}
public void Setcode (int code) {
this.code = code;
}
Public String getmsg () {return
msg;
}
public void Setmsg (String msg) {
this.msg = msg;
}
}
Helloworldserviceimpl.java
Package com.cwqsolo.demo.enitity;
public class Helloworldserviceimpl implements HelloWorldService {
int count=0;
Public Helloworldbean Getdemobean (string code, String msg) {
System.out.println ("Helloworldbean get");
Helloworldbean bean1 = new Helloworldbean ();
Bean1.setcode (Integer.parseint (code));
Bean1.setmsg (msg+ ", JavaBean is fine!");
return bean1;
}
Calculates the server-side count value and the public
integer getInt (integer code) {return
Code+count
}
for the code value that is passed in by the client. Returns the result of some string manipulation public
string getString (String msg) {return
msg+ ", Server is fine!";
}
The service side accepts the call and performs certain business actions. Here is count for technical public
void DoSomething () {
count++;
System.out.println ("Do something" + "; count=>" +count);
}
2 Service-side code
Jsonrpcservice.java
Package com.cwqsolo.demo.server;
Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Com.cwqsolo.demo.enitity.HelloWorldService;
Import Com.cwqsolo.demo.enitity.HelloWorldServiceImpl;
Import Com.googlecode.jsonrpc4j.JsonRpcServer;
public class Jsonrpcservice extends HttpServlet {private static final long serialversionuid = 1L;
Private Jsonrpcserver rpcserver = null;
Public Jsonrpcservice () {super (); The server generates the Helloworldserviceimpl object and provides the corresponding method rpcserver = new Jsonrpcserver (new Helloworldserviceimpl (), Helloworldserv
Ice.class); @Override protected void Service (HttpServletRequest request, httpservletresponse response) throws S
Ervletexception, IOException {System.out.println ("Jsonrpcservice service being call"); Rpcserver.handle (Request, ResponSE); }
}
3) Client Code
Package com.cwqsolo.demo.client;
Import Java.net.URL;
Import Java.util.HashMap;
Import Java.util.Map;
Import Com.cwqsolo.demo.enitity.HelloWorldBean;
Import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
public class jsonrpcclient{static jsonrpchttpclient client; Public jsonrpcclient () {} public static void Main (string[] args) throws Throwable {//instantiated request address, note service side W Configure the address in Eb.xml try {client = new Jsonrpchttpclient (The new URL ("http://127.0.0.1:8080/
Studyjsonrpc4j/rpc "));
The information added in the request header, here you can define map<string, string> headers = new hashmap<string, string> ();
Headers.put ("Name", "Key");
Add to the request header to client.setheaders (headers);
The client Dosomethine method by calling the remote object's dosomething jsonrpcclient test = new Jsonrpcclient (); Client Getdemo, is the Helloworldbean helloworldbe that gets the remote objectAn demo = Test.getdemo (1, "Hello");
Executes the remote object's Get method System.out.println ("++++++ call remote JavaBean obj function ++++++");
System.out.println (Demo.getcode ());
System.out.println (Demo.getmsg ());
Methods for executing remote objects int code = TEST.GETINT (10);
System.out.println ("++++++ call remote function Integer:first ++++++");
SYSTEM.OUT.PRINTLN (code);
Invoke the service-side DoSomething Method Test.dosomething ();
The second call to the remote object's GetInt Method code = Test.getint (10);
System.out.println ("++++++ call remote function Integer:second ++++++");
SYSTEM.OUT.PRINTLN (code);
String msg = test.getstring ("Hello");
System.out.println ("++++++ call remote function String ++++++");
SYSTEM.OUT.PRINTLN (msg); System.out.println ("++++++ End ++++++ ");
catch (Exception e) {e.printstacktrace ();
}/* * Client DoSomething method that invokes the dosomething/public void dosomething () throws Throwable {
Client.invoke ("dosomething", null); /* * Client Getdemo method, invoke Getdemo/public helloworldbean getdemo (int code, String msg) throws Throwab
Le {string[] params = new string[] {string.valueof (code), MSG};
Helloworldbean demo = null;
Demo = Client.invoke ("Getdemobean", params, helloworldbean.class);
return demo; /* * Client getInt is the calling service-side GetInt method/public int getInt (int code) throws Throwable {integer[] Cod
ES = new integer[] {code};
Return Client.invoke ("GetInt", Codes, Integer.class);
/* * Client getString is the calling service-side getString method/public String getString (String msg) throws Throwable {
string[] msgs = new string[] {msg}; Return Client.invoke ("getString ", msgs, String.class); }
}
3.3 Running and testing:
1 Service-side startup:
In the MyEclipse environment, start the server
Info: Starting Servlet engine:apache tomcat/7.0.30
December 12, 2016 4:49:56 pm Org.apache.catalina.startup.HostConfig depl Oydirectory
Information: Deploying Web application Directory E:\cwqwork\MyEclipse_Workspace\.metadata\.me_tcat7\webapps\ studyjsonrpc4j
December 12, 2016 4:49:58 pm org.apache.coyote.AbstractProtocol start
Info: Starting Protocolhandler [" http-bio-8080 "]
December 12, 2016 4:49:58 pm org.apache.coyote.AbstractProtocol start
Info: Starting Protocolhandler [ "ajp-bio-8009"]
December 12, 2016 4:49:58 pm Org.apache.catalina.startup.Catalina start
Info: Server Startup in 2340 MS
You can see the printed log:
Info: Deploying Web application Directory E:\cwqwork\MyEclipse_Workspace\.metadata\.me_tcat7\webapps\StudyJsonrpc4j-- -Represents a project to be published in a Tomcat environment, loaded after Tomcat starts
Server Startup in 2340 ms----indicates that Tomcat started successfully
2) client program calls
Directly run the client program to invoke, in the client code class, right-click to run:
++++++ call remote JavaBean obj function ++++++
1
hello,javabean is fine!
++++++ Call remote function Integer:first ++++++
++++++ call remote function Integer:second ++++++
11
++++++ Call remote function String ++++++
hello,server is fine!
++++++ End ++++++
You can see the First,second call, which results in a different result, indicating that the data on the server side was overwritten after the first call
3 The direct browser get way call, take the code with DoSomething method as an example
Http://127.0.0.1:8080/StudyJsonrpc4j/rpc?method=doSomething&id=1234¶ms=JTViJTVk
Description: PARAMS=JTVIJTVK, because the params parameter is empty, fill in [], need to convert to URL encoding, and then to Base64 encoding, this code is JTVIJTVK
After the call, the client will be prompted to download, after downloading with the browser to open, inside is the call returned content
Service-Side printing
Jsonrpcservice service being call do
something; count=>3
4 can use the Postman tool to test, using the Get method, post method can be successful
Using the Get method:
In the first red box, enter: Http://127.0.0.1:8080/StudyJsonrpc4j/rpc?method=doSomething&id=1234¶ms=JTViJTVk
After the second red box is send, the content returned
Using the Post method:
By post, URL is: HTTP://127.0.0.1:8080/STUDYJSONRPC4J/RPC, click on the params button, in the body, fill in the JSON string
{' method ': ' dosomething ', ' params ': [], ' ID ': 1234}
After the Send button, you can see the return content in the return area.