从Java中进行Json-Rpc调用

6
我正在编写一款运行于本地机器上的Java应用程序,它需要与另一个程序(也运行在本地机器上)进行交互。该程序具有JSON RPC API,这是与其进行交互的最佳方式。然而,在搜索过程中,我发现了很多用于从Java应用程序公开JSON RPC方法的库,但没有找到如何调用远程JSON方法的好方法。我该如何做到这一点?
我需要以下两个方面的帮助:
1.创建新的JSON对象以发送
2.连接到其他程序并发送我的响应
3.解码JSON响应
4个回答

3
我已经找到了几个很好的Java JSON-RPC库。两者都是免费的。JSON-RPC 2 的质量非常高,我也可以推荐他的其他作品。jsonrpc4j 看起来很完整,但我没有使用过。这些库都解决了一些问题,因此您不必处理底层实现。
此外,Google GSON 是一个将Java对象序列化为JSON的强大库。如果您有复杂的API,它可以极大地帮助你。

2
与JSON文本在Java中的交互,请参见Java中的JSON。使用它来构建JSON请求对象并将它们序列化为文本,以及从RPC服务器反序列化响应。
这是通过HTTP还是普通TCP连接进行的?如果是前者,请使用HTTPClient。如果是后者,则只需打开套接字并使用其I/O流。

0
这里有一些源代码示例和项目,可以演示如何创建自己的内容... 1. 创建新的JSON对象以发送
    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;
        }

源代码改编自:https://code.google.com/p/android-json-rpc/source/browse/trunk/android-json-rpc/src/org/alexd/jsonrpc/JSONRPCClient.java?r=47

或者使用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();

来自json-rpc-clientorg/json/rpc/client/JsonRpcInvoker.java

2. 连接到其他程序并发送响应的方法

使用HTTP,您可以执行以下操作:

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();
    }
}

源代码改编自json-rpc-clientorg/json/rpc/client/HttpJsonRpcClientTransport.java

3. 解码JSON响应的方法

读取HTTP响应,然后解析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

请注意,我是从现有的JSON RPC客户端库中组合这些代码片段的,因此这些代码没有经过测试,可能无法直接编译,但应该可以为您提供一个很好的基础。


-2

JSON库用于创建JSON对象: http://www.json.org/java/, Lib:http://json-lib.sourceforge.net/

首先,JSON调用将是对某个URL的AJAX调用。该URL必须返回内容类型设置为“application/json”的JSON内容。

您可以创建一个新的servlet,在响应中设置上述内容类型,创建新的JSONObject,将您的对象放入其中,并将JSONObject.toString()写入响应中。

因此,客户端将获取JSON字符串。您可以使用简单的Javascript或jQuery访问它。

您可以为JSON支持制作一个特殊的servlet,该servlet仅处理JSON AJAX请求并返回适当的JSON响应。

parth。


1
这似乎是在描述如何构建一个接收请求并以JSON格式返回响应的Web服务。提问者似乎对如何从普通Java应用程序中使用JSON RPC服务感兴趣。 - Alan Krueger
2
无论如何...你也指定了我指定的相同的事情...JSON.org :) - Parth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接