Вот несколько исходных примеров и проектов, которые вы можете посмотреть, чтобы продемонстрировать, как вы можете создать свой собственный ...
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();
Из org / json / rpc / client / JsonRpcInvoker.java из json-rpc-client
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();
}
}
Источник адаптирован из org / json / rpc / client / HttpJsonRpcClientTransport.java из json-rpc-client
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, так что это не проверено и может не скомпилироваться как есть, но должно дать вам хорошую основу для работы.