【问题标题】:Making Json-Rpc calls from java从 java 进行 Json-Rpc 调用
【发布时间】:2011-03-16 03:31:53
【问题描述】:

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

我正在寻找的两件事是:

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

【问题讨论】:

    标签: java json rpc


    【解决方案1】:

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

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

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

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

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

    部分。

    【讨论】:

    • 这似乎是在描述如何构建一个以 JSON 格式接收请求并返回响应的 Web 服务。提问者似乎对如何从普通 Java 应用程序使用 JSON RPC 服务感兴趣。
    • 无论如何...你还指定了我指定的相同内容... JSON.org :)
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        这里有一些源示例和项目可供查看,以展示您如何创建自己的...

        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
        

        请记住,我将这些 sn-ps 来自现有的 JSON RPC 客户端库,因此未经测试,可能无法按原样编译,但应该为您提供良好的工作基础。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-12-02
          • 1970-01-01
          • 2022-08-16
          • 2013-11-24
          • 2010-09-18
          • 2023-03-31
          • 1970-01-01
          相关资源
          最近更新 更多