繁体   English   中英

从java进行Json-Rpc调用

[英]Making Json-Rpc calls from java

我正在编写一个在本地机器上运行的java应用程序,它需要与另一个程序交互(也在本地机器上运行),另一个程序有一个JSON RPC API,这是与它交互的最佳方式。 但是,在谷歌搜索中我发现了很多用于从Java应用程序公开JSON RPC方法的库,但是没有什么好的方法可以调用远程JSON方法。 我该怎么做?

我正在寻找的两件事是:

  1. 一种创建要发送的新JSON对象的方法
  2. 一种连接到其他程序并发送我的响应的方法
  3. 一种解码JSON响应的方法

我找到了几个非常好的Java JSON-RPC库。 两者都是免费的。 JSON-RPC 2质量非常高,我还可以推荐他的一些其他作品。 jsonrpc4j似乎完整,但我还没用过它。 这两个库都解决了几个问题,因此您不必处理低级实现。

此外, Google GSON是一个非常棒的库,用于将Java对象序列化为JSON。 如果您有一个复杂的API,它可以帮助很大。

要在Java中与JSON文本交互,请参阅Java中的JSON 使用它来构建JSON请求对象并将它们序列化为文本以及从RPC服务器反序列化响应。

这是通过HTTP还是普通的TCP连接? 如果是前者,请使用HTTPClient 如果是后者,只需打开一个套接字并使用其I / O流即可。

以下是一些源代码示例和项目,以展示如何创建自己的...

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-client的 org / 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-client的 org / 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客户端库中放在一起,因此未经过测试,可能无法按原样编译,但应为您提供良好的工作基础。

JSON库usefule用于制作JSON对象: http//www.json.org/java/,Libhttp ://json-lib.sourceforge.net/

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

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

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

您可以仅为JSON支持创建一个特殊的servlet,它只支持JSON AJAX请求并返回正确的JSON响应。

PARTH。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM