Making Json-Rpc calls from java

I am writing a java application that runs on the local machine, it needs to interact with another program (also running on the local machine), the other program has the JSON RPC API, which is the best way to interact with it, However, when searching in googling I found many libraries for demonstrating JSON RPC methods from a Java application, but nothing good about calling the remote JSON method. How can I do it?

The two things I'm looking for are the following:

  • The way to create new JSON objects is to send
  • Way to connect to another program and send my answer
  • JSON response decoding method
+4
source share
4 answers

For interacting with JSON text in Java, see JSON in Java . Use this to create JSON request objects and serialize them for text, as well as to de-serialize the response from the RPC server.

Is it over HTTP or a simple TCP connection? If the first, use HTTPClient . If the latter, just open the socket and use its I / O streams.

+1
source

I found a 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 work. jsonrpc4j seems complete, but I have not used it. Both of these libraries solve several problems, so you do not need to deal with low-level implementation.

In addition, Google GSON is a terrific library for serializing Java objects to JSON. If you have a complex API, it can help a lot.

+1
source

Here are some initial examples and projects where you can see how you can create 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 json-rpc-client

2. A way to connect to another program and send my answer

Using HTTP, you can 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 json-rpc-client

3. Method for decoding 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 that these fragments compose together with existing JSON RPC client libraries, so this is not verified and may not compile as is, but should give you a good basis for working.

0
source

The JSON library is used to create JSON objects: http://www.json.org/java/ , Lib: http://json-lib.sourceforge.net/

First of all, a JSON call will be an AJAX call to some URL. The URL should return JSON content with the content type set to "application / json".

You can create a new servlet in response to the above content type, Create a new JSONObject , put your objects in it and write the response JSONObject.toString() .

Thus, the client will receive a JSON string. You can access it using simple Javascript OR jQuery.

You can create a custom servlet for JSON support only, which only requests AJAX JSON and returns the correct JSON responses.

Parth.

-2
source

Source: https://habr.com/ru/post/1315736/


All Articles