Making Json-Rpc calls from java
I'm writing a java application which runs on the local machine, it ne开发者_开发技巧eds to interact with another program (also running on the local machine), the other program has a JSON RPC API which is the best way to interact with it. However, in googling around I found a lot of libraries for exposing JSON RPC methods from a java application but nothing good on how to call a remote JSON method. How would I do this?
The two things I'm looking for are:
- A way to create new JSON objects to send
- A way to connect to the other program and send my response
- A way to decode the JSON response
I have found couple of very good Java JSON-RPC libraries. Both are free. JSON-RPC 2 is of really high quality, and I can also recommend some of his other works. jsonrpc4j seems complete, but I have not used it. Both of these libraries solve several problems, so that you do not have to deal with low level implementation.
In addition, Google GSON is an awesome library for serializing Java objects into JSON. If you have a complicated API, it can help greatly.
For interacting with JSON text in Java, see JSON in Java. Use this for building JSON request objects and serializing them to text as well as de-serializaing the response from the RPC server.
Is this over HTTP or a plain TCP connection? If the former, use HTTPClient
. If the latter, just open a socket and use its I/O streams.
Here are some source examples and projects to look at to demonstrate how you might go about creating your own...
1. A way to create new JSON objects to send
import java.util.UUID;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
protected JSONObject toJSONRequest(String method, Object[] params) throws JSONRPCException
{
//Copy method arguments in a json array
JSONArray jsonParams = new JSONArray();
for (int i=0; i<params.length; i++)
{
if(params[i].getClass().isArray()){
jsonParams.put(getJSONArray((Object[])params[i]));
}
jsonParams.put(params[i]);
}
//Create the json request object
JSONObject jsonRequest = new JSONObject();
try
{
jsonRequest.put("id", UUID.randomUUID().hashCode());
jsonRequest.put("method", method);
jsonRequest.put("params", jsonParams);
}
catch (JSONException e1)
{
throw new JSONRPCException("Invalid JSON request", e1);
}
return jsonRequest;
}
Source adapted from: https://code.google.com/p/android-json-rpc/source/browse/trunk/android-json-rpc/src/org/alexd/jsonrpc/JSONRPCClient.java?r=47
Or using GSON:
Gson gson = new Gson();
JsonObject req = new JsonObject();
req.addProperty("id", id);
req.addProperty("method", methodName);
JsonArray params = new JsonArray();
if (args != null) {
for (Object o : args) {
params.add(gson.toJsonTree(o));
}
}
req.add("params", params);
String requestData = req.toString();
From org/json/rpc/client/JsonRpcInvoker.java of json-rpc-client
2. A way to connect to the other program and send my response
Using HTTP, you could do the following:
URL url = new URL("http://...");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
OutputStream out = null;
try {
out = connection.getOutputStream();
out.write(requestData.getBytes());
out.flush();
out.close();
int statusCode = connection.getResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
throw new JsonRpcClientException("unexpected status code returned : " + statusCode);
}
} finally {
if (out != null) {
out.close();
}
}
Source adapted from org/json/rpc/client/HttpJsonRpcClientTransport.java of json-rpc-client
3. A way to decode the JSON response
Read the HTTP response and then parse the JSON:
InputStream in = connection.getInputStream();
try {
in = connection.getInputStream();
in = new BufferedInputStream(in);
byte[] buff = new byte[1024];
int n;
while ((n = in.read(buff)) > 0) {
bos.write(buff, 0, n);
}
bos.flush();
bos.close();
} finally {
if (in != null) {
in.close();
}
}
JsonParser parser = new JsonParser();
JsonObject resp = (JsonObject) parser.parse(new StringReader(bos.toString()));
JsonElement result = resp.get("result");
JsonElement error = resp.get("error");
// ... etc
Keep in mind I put these snippets together from existing JSON RPC client libraries, so this is not tested and may not compile as is, but should give you a good basis to work from.
JSON library usefule to make JSON objects: http://www.json.org/java/ , Lib: http://json-lib.sourceforge.net/
First thing is, JSON call will be AJAX call to some URL. The URL must return JSON content with content type set to "application/json".
You can make a new servlet, in response set above content type, Make new JSONObject
, put your objects in it and write the JSONObject.toString()
to response.
So the client will get the JSON String. You can access it using simple Javascript OR jQuery.
You can make a special servlet only for JSON support which only haqndles JSON AJAX requests and returns proper JSON responses.
parth.
精彩评论