这里有一些源示例和项目可供查看,以展示您如何创建自己的...
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
请记住,我将这些 sn-ps 来自现有的 JSON RPC 客户端库,因此未经测试,可能无法按原样编译,但应该为您提供良好的工作基础。