我需要以下两个方面的帮助:
1.创建新的JSON对象以发送
2.连接到其他程序并发送我的响应
3.解码JSON响应
HTTPClient
。如果是后者,则只需打开套接字并使用其I/O流。 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;
}
或者使用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库用于创建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。